Showing posts with label selenium. Show all posts
Showing posts with label selenium. Show all posts

Tuesday, October 20, 2015

Latest Selenium-Server-Standalone Jar




Selenium latest version jar is available now with many issues fixes. Java change log available here.





Released on : 09-Oct-2015
Version : 2.48
Download Link : Click Here

Released on : 30-Jul-2015
Version : 2.47
Download Link : Click Here

Released on : 04-Jun-2015
Version : 2.46
Download Link : Click Here





Saturday, September 14, 2013

Locating WebElements Using XPath







   In automation locating web elements in DOM is one of the important task. In DOM, if all the elements have unique ids then no problem but, if not we need to go for xpath for locating elements in DOM.

  Say for example generally we don't see any ids for the table rows & columns, in that case we need to locate table data using some other attributes. Ex: name, position, innerText.

  Below I'm writing simple example to understand the different options available in xpath. (Place mouseover the locator to see which element it will locate in table)

HTML Elements


Above html in browser

One Bike
Two Car
Three Bus
Four Jeep

Locating elements using Attributes

AttributeUsage
idBy.xpath("//table[@id='tableId']")
idBy.xpath("//td[@id='car']")
nameBy.xpath("//td[@name='Chk3']")


Locating Rows using index

RowAs a child As a sub-child
1By.xpath("//table[@id='tableId']/tbody/tr[1]")By.xpath("//table[@id='tableId']//tr[1]")
2By.xpath("//table[@id='tableId']/tbody/tr[2]")By.xpath("//table[@id='tableId']//tr[2]")
3By.xpath("//table[@id='tableId']/tbody/tr[3]")By.xpath("//table[@id='tableId']//tr[3]")
4By.xpath("//table[@id='tableId']/tbody/tr[4]")By.xpath("//table[@id='tableId']//tr[4]")

Locating Rows using functions

FunctionAs a child
position()By.xpath("//table[@id='tableId']//tr[position()=1]")
position()By.xpath("//table[@id='tableId']//tr[position()=3]")
last()By.xpath("//table[@id='tableId']//tr[last()]")
last()By.xpath("//table[@id='tableId']//tr[last()-1]")

Locating Rows using String functions

FunctionUsage
text()By.xpath("//table[@id='tableId']//tr/td[text()='One']")
contains()By.xpath("//table[@id='tableId']//tr/td[contains(text(),'hre')]")
starts-with()By.xpath("//table[@id='tableId']//tr/td[start-with(text(),'Fo')]")

Locating Columns using Xpath Axes

AxesUsage
childBy.xpath("//table[@id='tableId']//tr/child::td[text()='One']")
parentBy.xpath("//td[@id='car']/parent::tr")
preceding-siblingBy.xpath("//td[contains(@id,'bus')]/preceding-sibling::td/input")
following-siblingBy.xpath("//td[text()='Four']/following-sibling::td[@id='jeep']")
  • Child : Selects all children of the current node.
  • Parent : Selects the parent of the current node.
  • preceding-sibling:Selects all siblings before the current node.
  • following-sibling:Selects all siblings after the current node.

Happy Coding :)


Regards,
SantoshSarma



Friday, September 13, 2013

Generating Random Data





Generating Random Data
Say , you are running RecordCreate/FormFilling automation for 100 times.
  1. Passing every time same values (Hardcoded values)
  2. Passing randomly generated values from allowed characters
Which one is more reliable ? 

How will you verify forms by filling allowed max length values ?


Let's see how to fill the forms in web application with random & specified length values.

Consider below form

You want to fill below form with randomly generated values with specified lengths.

Register here

First Name
Last Name
Email
Phone
Income


See below testcase to know how can we pass random & specified length values to different fields.

RegistrationForm.java


package com.test.registration;

import static org.junit.Assert.assertEquals;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import com.test.general.GenerateData;

public class RegistrationForm {
 
 WebDriver driver;
 GenerateData genData;
 
 @Before
 public void before(){
  driver=new FirefoxDriver();
  genData=new GenerateData();
 }
 
 @Test
 public void testRegistrationForm() {
  driver.findElement(By.id("f_name")).sendKeys(genData.generateRandomAlphaNumeric(30));    
  driver.findElement(By.id("l_name")).sendKeys(genData.generateRandomString(20));
  driver.findElement(By.id("email")).sendKeys(genData.generateEmail(30));
  driver.findElement(By.id("skype")).sendKeys(genData.generateStringWithAllobedSplChars(30, "abc123_-."));
  driver.findElement(By.id("phone")).sendKeys(genData.generateRandomNumber(10));
  driver.findElement(By.id("income")).sendKeys(genData.generateRandomNumber(9));
  driver.findElement(By.id("submit")).click();
  assertEquals("Success", driver.getTitle());
 }
 
 @After
 public void after(){
  driver.quit();
 }

}




GenerateData.java


package com.test.general;

import org.apache.commons.lang3.RandomStringUtils;

public class GenerateData {

 public String generateRandomString(int length){
  return RandomStringUtils.randomAlphabetic(length);
 }
 
 public String generateRandomNumber(int length){
  return RandomStringUtils.randomNumeric(length);
 }
 
 public String generateRandomAlphaNumeric(int length){
  return RandomStringUtils.randomAlphanumeric(length);
 }
 
 public String generateStringWithAllobedSplChars(int length,String allowdSplChrs){
  String allowedChars="abcdefghijklmnopqrstuvwxyz" +   //alphabets
    "1234567890" +   //numbers
    allowdSplChrs;
  return RandomStringUtils.random(length, allowedChars);
 }
 
 public String generateEmail(int length) {
  String allowedChars="abcdefghijklmnopqrstuvwxyz" +   //alphabets
    "1234567890" +   //numbers
    "_-.";   //special characters
  String email="";
  String temp=RandomStringUtils.random(length,allowedChars);
  email=temp.substring(0,temp.length()-9)+"@test.org";
  return email;
 }
 
 public String generateUrl(int length) {
  String allowedChars="abcdefghijklmnopqrstuvwxyz" +   //alphabets
    "1234567890" +   //numbers
    "_-.";   //special characters
  String url="";
  String temp=RandomStringUtils.random(length,allowedChars);
  url=temp.substring(0,3)+"."+temp.substring(4,temp.length()-4)+"."+temp.substring(temp.length()-3);
  return url;
 }
}
 

    While doing web application automation make a habit of passing random data with different lengths (<= Allowed max length) every time to improve reliability.


Related Topics
Generating Dynamic Dates



Saturday, April 20, 2013

Print table data






Locating table rows and cells
 Sometimes we need to iterate through out table and do some operations with that.

Example :

  1. Verify for expected values in table
  2. Sort  table columns in ascending & descending order and verify.
In above both the cases we need to get the table data to verify. Lets see how to get the data from table.
Steps
  • get table instance
  • using above table instance , get all table rows
  • iterate each row and get all columns values.
Logic


@Test
public void testTable()
{
          WebElement table = driver.findElement(By.id("tableId"));
       
          //Get all rows (tr tags)
          List<WebElement> rows = table.findElements(By.tagName("tr"));

           //Print data from each row (Data from each td tag)
           for (WebElement row : rows) {
           List
<WebElement> cols = row.findElements(By.tagName("td"));
                  for (WebElement col : cols) {
                        System.out.print(col.getText() + "\t");
                  }
          System.out.println();
          }
}


Happy Coding :)


Regards,
SantoshSarma




Saturday, April 6, 2013

Choosing options from Dropdown - WebDriver






In web application we see many drop down lists for many input fields (Ex : gender, age, country..etc). This drop down option is different from normal text/numeric input field. It has separate tag <select></select>in html.

In automation while filling most of the forms we need to fill/select the drop down values also. For achieving this WebDriver has separate class called Select.

In this post we will see what are all different method available in Select class.

Consider below example

                  HTML CODE
                                         <select id="city">
                                               <option value="Op1">Chennai</option>
                                               <option value="Op2">Hyderabad</option>
                                               <option value="Op3">Bangalore</option>
                                         </select>

Select an Option
Available methods for selecting an option are
  1. selectByIndex(int index)
  2. selectByValue(java.lang.String value)
  3. selectByVisibleText(java.lang.String text)
selectByIndex(int index)
Select the option at the given index.
Usage :
new Select(driver.findElement(By.id("city"))).selectByIndex(2);
In above example it will select the Hyderabad because it is in index 2.

selectByValue(java.lang.String value)
Select all options that have a value matching the argument.
Usage :
new Select(driver.findElement(By.id("city"))).selectByValue("Op3");
In above example it will select the Bangalore  based on the value attribute of that option.

selectByVisibleText(java.lang.String text)
Select all options that display text matching the argument.
Usage :
new Select(driver.findElement(By.id("city"))).selectByVisiableText("Chennai");
In above example it will select the Chennai based on the visible text.


De-select an option
Available methods for de-selecting an option(s) are,

  1. deselectAll()
  2. deselectByIndex(int index)
  3. deselectByValue(java.lang.String value)
  4. deselectByVisibleText(java.lang.String text)
deselectAll()
  • Clear all selected entries.
deselectByIndex(int index)
  • Deselect the option at the given index.
deselectByValue(java.lang.String value)
  • Deselect all options that have a value matching the argument.
deselectByVisibleText(java.lang.String text)
  • Deselect all options that display text matching the argument.


Getting all options
Some times we may in need to get all the options available in drop down list in that case below method will be useful.

  • getOptions();
getOptions()
It will return All options belonging to this select tag
Usage :
List<WebElement> allCities=new Select(driver.findElement(By.id("city"))).getOptions();
for(WebElement city:allCities)
{
      System.out.println(city.getText());    //It will return the text of each option
      System.out.println(city.getAttribute("value"));    //it will return the value attribute of each option
}

Get Selected Option(s)
If you want to verify whether the proper value got selected in particular drop down list you can make use of below methods.


  1. getFirstSelectedOption();
  2. getAllSelectedOptions() ;
getFirstSelectedOption();
  • The first selected option in this select tag (or the currently selected option in a normal select)
getAllSelectedOptions() ;
  • It will return List of All selected options belonging to this select tag. (This will be useful for multiselect picklist)

Handling multi-select pick list

                 HTML CODE
                                         <select id="city" multiple>
                                               <option value="Op1">Chennai</option>
                                               <option value="Op2">Hyderabad</option>
                                               <option value="Op3">Bangalore</option>
                                         </select>


Handling multi select pick list same as normal drop down( single pick list).
For selecting both Hyderabad, Bangalore option you need to use one of the below logics.

new Select(driver.findElement(By.id("city"))).selectByIndex(2);
new Select(driver.findElement(By.id("city"))).selectByIndex(3);
Or
new Select(driver.findElement(By.id("city"))).selectByvalue("Op2");
new Select(driver.findElement(By.id("city"))).selectByvalue("Op3");
Or
new Select(driver.findElement(By.id("city"))).selectByVisiableText("Hyderabad");
new Select(driver.findElement(By.id("city"))).selectByVisiableText("Bangalore");


I hope you understand WebDriver Select class usage in automation.


Happy Selecting :)


Regards,
SantoshSarma



Wednesday, March 27, 2013

Replace XPath with Css selector






If you know css selectors, those are much more easier (and will work fine with IE without any problem ) than xpath even though they can't replace entire xpath.


Consider below HTML tags


 <div id="firstDiv">This div tag has static id </div>

 <p id="paragraps_dynamic_1234">This p tag has dynamic id</p>

 <a onclick="doThat()" title="doThatOperation">This a tag has multiple attributes</a>

 <h1 name="heading1" value="headName">This is heading</h1>


<div>
<input type="text" id="username" name="username"
<input type="password" id="password" name="pwd"
</div>

<h2 id="propertyUserData">This tag is for starts-with example</h2>


Tag XPATH CSS SELECTOR
div "//div[@id='firstDiv']" "div[id='firstDiv']"
p "//p[contains(@id,'paragraps_dynamic_')]" "p[id*='paragraps_dynamic_']"
a "//a[contains(@onclick,'doThat') and @tile='doThatOperation']" "a[onclick*='doThat'][tile='doThatOperation']"
h1 "//h1[@name='heading1' and @value='headName']" "h1[name='heading1'][value='headName']"
input "//div/input[@id='username']" "div > input[id='username']"
input "//h2[starts-with(@id,'propertyUser')]" "h2[id^='propertyUser']"

By seeing above locators we can conclude some points regarding css selectors

  • Using css selector we can access particular node or immediate child of any node
  • Can combine as many conditions as we want for single node.
  • Can achieve starts-with, contains functionality using ^,* symbols respectively. 
  • We can't traverse back using css selector.
  • We can't go to  the siblings also (preceding as well as following)



Friday, February 1, 2013

Uploading photo in facebook using WebDriver

Automate Facebook with WebDriver
Uploading photo in facebook

driver.get("http://www.facebook.com");  
  driver.findElement(By.id("email")).clear();  
  driver.findElement(By.id("email")).sendKeys("*******@gmail.com");  
  driver.findElement(By.id("pass")).clear();  
  driver.findElement(By.id("pass")).sendKeys("*******");  
  driver.findElement(By.cssSelector("#loginbutton > input")).click();  
  driver.findElement(By.linkText("Facebook")).click();  
  driver.findElement(By.linkText("Add Photos/Video")).click();  
  driver.findElement(By.xpath("//div[text()='Upload Photos/Video']/
                           following-sibling::div/input")).sendKeys("C:\\MyPhoto.jpg");  

Monday, January 28, 2013

isTextPresent() ? In WebDriver

While automation web applications in some places we want/need to check particular text is present or not.

In WebDriver (Selenium 2), there is no predefined method for checking this. (In Selenium-RC isTextPresent("text") built-in method exist ) So we need to implement our own method to achieve this.


Let us consider you are searching for text "WebDriver"



boolean isTextPrest=false;

Method-1
 isTextPrest=driver.findElement(By.tagName("body")).getText().contains("WebDriver");  

Method-2
 isTextPrest=driver.findElement(By.xpath("//*[contains(.,'WebDriver')]")).isDisplayed();  

Method-3
 Selenium sel=new WebDriverBackedSelenium(driver, "");  
 isTextPresent=sel.isTextPresent("WebDriver");  


FYI : Method-1 will take more time than remaining (comparatively)

Happy Coding :)


Regards,
SantoshSarma

XPath indexing

Q : What does //td[2] mean?
A : All td elements in that page (document), that are second child of their parent.


Q : Will //td[2] return only one element?
A :  No, there may be many such elements. (second child td of their parent)


 if you've any doubts regarding this xpath indexing post it in comments section.



Related Topics
How to write xpath?
Locating elements using xpath




Tuesday, January 22, 2013

Finding elements within iframe using firebug


Firebug Tip

Firebug command line allows executing JavaScript expressions within context of the current page. Firebug also provides a set of built in APIs and one of them is cd().

Lets consider below iframe

                <iframe id="testID" name="testName" src="iframe.html" />


  • cd(document.getElementById("testID").contentWindow); switch to a frame by ID
  • cd(window.frames[0]); switch to the first frame in the list of frames
  • cd(window.frames["testName"]); switch to a frame using by name
  • cd(window.top); switching back to the top level window


Happy Coding .. :)


Regards,
SantoshSarma

Thursday, January 3, 2013

isElementPresent? Method another way





“we can use the findElements() call, and then we just need to check that the size of the list returned is 0.

You can write logic like this.

List elements = driver.findElements(By.Id("element id"));
if(elements.size()==0)
        No element found
else
        Element found



Saturday, October 13, 2012

Implicit wait Vs. Explicit wait

WebDriver Waits
Implicit wait

WebDriver driver = new FirefoxDriver();  
 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Implicit waits are basically your way of telling WebDriver the latency that you want to see if specified web element is not present that WebDriver looking for. So in this case, you are telling WebDriver that it should wait 10 seconds in cases of specified element not available on the UI (DOM).


  • Implicit wait time is applied to all elements in your script



Explicit wait (By Using FluentWait)

public static WebElement explicitWait(WebDriver driver,By by)  
{  
    Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)  
             .withTimeout(20, TimeUnit.SECONDS)  
             .pollingEvery(2, TimeUnit.SECONDS)  
             .ignoring(NoSuchElementException.class); 

     WebElement element= wait.until(new Function<WebDriver, WebElement>() {  
           public WebElement apply(WebDriver driver) {  
             return driver.findElement(By.id("foo"));  
            }  
      });  
  return 


Explicit waits are intelligent waits that are confined to a particular web element. Using explicit waits you are basically telling  WebDriver at the max it is to wait for X units of time before it gives up.

  •  In Explicit you can configure, how frequently (instead of 2 seconds) you want to check condition
  • Explicit wait time is applied only for particular specified element.
Explicit wait

public static WebElement explicitWait(WebDriver driver,By by)  
 {  
      WebDriverWait wait = new WebDriverWait(driver, 30);  
      wait.until(ExpectedConditions.presenceOfElementLocated(by));  
 }       

In above method it will wait until either ExpectedConditions become true or Timeout (30 sec).

Friday, July 20, 2012

How not to automate..!


       Whatever you do, do not simply distribute a testing tool among your testers and expect them to automate the test process. Just as you would never automate accounting by giving a program compiler to the accounting department, neither should you attempt to automate testing by just turning a testing tool over to the test group.
   It is important to realize that test automation tools are really just specialized programming languages, and developing an automated test library is a development project requiring commensurate skills.


Automation is more than capture/replay
If you acquired a test tool with the idea that all you have to do is record and playback the tests, you are due for disappointment. Although it is the most commonly recognized technique, capture/replay is not the most successful approach. Selecting an Automation Approach, capture and replay does not result in a test library that is robust, maintainable or transferable as changes occur.


Don’t write a program to test a program!
The other extreme from capture/replay is pure programming. But if you automate your tests by trying to write scripts that anticipate the behavior of the underlying program and provide for each potential response, you will essentially end up developing a mirror version of the application under test! Where will it end? Who tests the tests? Although appealing to some, this strategy is doomed - no one has the time or resources to develop two complete systems.   Ironically, developing an automated test library that provides comprehensive coverage would require more code than exists in the application itself! This is because tests must account for positive, negative, and otherwise invalid cases for each feature or function.


Duplication of effort
The problem is, if you just hand an automation tool out to individual testers and command that they automate their tests, each one of them will address all of these issues - in their own unique and Introduction personal way, of course. This leads to tremendous duplication of effort and can cause conflict when the tests are combined, as they must be.


Automation is more than test execution
So if it isn’t capture/replay and it isn’t pure programming, what is it? Think of it this way. You are going to build an application that automates your testing, which is actually more than just running the tests. You need a complete process and environment for creating and documenting tests, managing and maintaining them, executing them and reporting the results, as well as managing the test environment. Just developing scores of individual tests does not comprise a strategic test automation system.



Need for a framework
Instead, approach the automation of testing just as you would the automation of any application - with an overall framework, and an orderly division of the responsibilities. This framework should make the test environment efficient to develop, manage and maintain. 

Remember, test tools aren’t magic - but, properly implemented, they can work wonders!

Saturday, July 14, 2012

How to write Xpath ?





How to write Xpath?
In Selenium-Rc/WebDriver automation xpath is the one of the way to locate elements on webpage.XPath uses path expressions to select nodes/element in an XML/ HTML document.

How to verify in firebug?
  • Open firebug in firefox/Chrome.
  • Go to console.
  • type : $x("<xpath>").
  • Hit Enter.
  • If it is correct path you can element in that console. If you mouse hover on that, the element will highlight in web page.
Example:


How to write Xpath?
Examples
Facebook signup form
1. Select first name
 //input[@id='firstname]     OR       //input[@name=firstname]   
In this case no need of xpath locator because we can use By.id, By.name,By.cssSelector.
By.id("firstname")    |   By.name("firstname")  | By.cssSelector("[id=firstname]")

2. Selecting first name input using First Name label
 //label[text()='First Name:']/parent::td/following-sibling::td/div/input  
                          or  
      //label[text()='First Name:']/../../td/div/input  
In above example,
parent This keyword helps you to back track to parent node from child node.
following-sibling This keyword helps you to go following-sibling.
preceding-sibling This keyword helps you to go preceding-sibling.
.. This also helps you to go parent node from child node
See below table for more keywords
3. Using contains, starts-with

Select Last Name using contains //label[contains(text(),'Last')]/../../td/div/input
Select Last Name using starts-with //label[starts-with(text(),'Last')]/../../td/div/input

4. Index/position based

5. Some more expressions


If you have any doubts in xpath..Post your html code snippet here I would try to give you solution.


Happy Coding..! 

Regards,
Santosh



Tuesday, April 24, 2012

QTP Vs. Selenium


It is good news for all Selenium testers...!






Friday, April 20, 2012

Overcoming the Automation Challenges Using Selenium


Selenium is an Open Source Tool developed by ThoughtWorks. There are a set of Selenium tools which when combined provides you the power to automate simple to complex web application. Some of the Selenium Tool under ThoughtWorks umbrella are:

Selenium IDE – It is a Firefox add-on that makes it easy to record and playback tests in Firefox 2+. You can even use it to generate code to run the tests with Selenium Remote Control.

Selenium Remote Control (RC) – It is a client/server system that allows you to control web browsers locally or on other computers, using almost any programming language and testing framework.

Selenium Grid – It takes Selenium Remote Control to another level by running tests on many servers at the same time and cutting down on the time it takes to test multiple browsers or operating systems.

Bromine – It is a web-based QA tool of Selenium that enables you to easily run Selenium RC tests and view the results. It scales beautifully, from the single tester who just wants to run some tests without all the hassle; to the corporate solution, with multiple user-groups and hundreds of test cases.

Selenium is the best open source tool for doing automation for web based application and it does not have any cost attached to it. The only cost is the effort which will go for designing and developing the script for the application.

There is no need to define or develop separate Life Cycle for doing automation in Selenium. If you have an existing automation process, Selenium Automation Life Cycle will fit into that well. If you are using Selenium as an automation tool, you will find a lot of information online for the best process or Life Cycle to be adopted for automation.

Selenium scripting can be done in a number of programming languages like C#, Perl, PHP, Ruby, Java etc, unlike other commercial tools which support single scripting language. Since Selenium scripting can be done in any language of choice, one can easily find right resources for the programming language chosen for Selenium Automation.

Last but not the least, since this tool comes at ZERO PRICE, an organization’s management will find that the only investment they have made is on the infrastructure and human effort and not on the heavy licensing cost.




Thursday, April 19, 2012

JUnit Fundamentals






  • JUnit was created as a framework for writing automated, self-verifying tests in Java, which in JUnit are called test cases.
  • JUnit provides a natural grouping mechanism for related tests, which is called a test suite.
test case Vs TestCase class
  • test case generally refers to single test, verifying a specfic path through code.
  • To collect multiple test cases into a single class, itself a subclass of TestCase, with each test case implemented as a method on TestCase.
  • test case class is called fixture.
  • The TestCase class provides a default mechanism for identifying which methods are tests, but U can collect the tests urself in customized suites.
Points to Remember
  • As long as you follow a few simple rules, JUnit will find ur tests and execute them:
  • ur test methods must be instace level, take no parameteras, and return nothing. must declare them as a public void testMethodName().
  • The name of ur test method must start with 'test' all lowercase.
How To write simple JUnit
  • Create a subclass of TestCase
  • To create a test, write a method that expresses the test. Using a JUnit naming conventio that allows JUnit to find and execute ur test automatically.
  • U place the method in a class that extends the JUnit framework class TestCase.
  • To express how U expect the object to behave, you make assertions. (An assertion is simply a statement of ur expectation).
  • TestCase class is the center of the JUnit framework. TestCase in the package junit.framework.
TestSuite
  • A TestSuite is a Composite of Tests. It runs a collection of test cases.
  • A TestSuite can extract the tests to be run automatically. To do so you pass the class of your TestCase class to the TestSuite constructor.
TestCase
  • A test case defines the fixture to run multiple tests. To define a test case
  • implement a subclass of TestCase
  • define instance variables that store the state of the fixture
  • initialize the fixture state by overriding setUp()
  • clean-up after a test by overriding tearDown().
  • Each test runs in its own fixture so there can be no side effects among test runs.
Assertions
  • The class TestCase extends a utility class named Assert in the JUnit framework.
  • The Assert class provides the methods you will use to make assertions about the state of ur objects.
methods of Assert class is
  1. assertTrue(boolen condition)
  2. assertEquals(Object expected,object actual)
  3. assertEquals(int expected,int actual)
  4. assertSame(Object expected,object actual)
  5. assertNull(Object object).
Failure msgs
  • When assertion fails, it is worth including a short msg that indicates the nature of the failure, even a reason for it.
  • Each of the assertion methods accepts as an optional first parameter a String containing a msg to display when the assertion fails.
  • also assertion methods has its own customized failure msgs.
  • when an assertion fails, the assertion method throws an error: an assertionFailedError.
Failure Vs Error
  • JUnit throws an error rather than an expection because in Java, errors are unchecked:
  • When ur test contains a failed assertion, JUnit counts that as a failed test; but when ur test throws an expection(and does not catch it), JUnit counts that as an error.
Test has three basic parts
  1. Create objects.
  2. Invoke some objects.
  3. Check the results.
Note
  • In JUnit, the smallest unit of "test execution" is the test suite. JUnit doesn't actually execute individual tests,
  • but only executes test suites, so in order to execute ur test, U neeed to collect them into a test suite.
  • note that each test runs in its own instance of your test case class.
  • This is one of the fundamental aspects of JUnit's design.
TestResult
  • A TestResult collects the results of executing a test case. It is an instance of the Collecting Parameter pattern. 
  • The test framework distinguishes between failures and errors. 
  • A failure is anticipated and checked for with assertions.
  • Errors are unanticipated problems like an ArrayIndexOutOfBoundsException.
TestFailure
  • A TestFailure collects a failed test together with the caught exception.
How to create testsuite?
  • Create a method on ur test case class called suite(). IT must declared as public static Test suite(), taking no parameters and returning a Test object.
  • In the body of suite method, crete a TestSuite object, and then add Test objects to suite:(either individual tests or other test suites).
  • Return this TestSuite object.
==>manually building a test suite
TestSuite suite=new TestSuite();
suite.addTest(new MoneyTest("testEquals"));
suite.addTest(new MoneyTest("testSimpleAdd"));
==>Passing the TestCase class to TestSuite
return new TestSuite(MoneyTest.class);
  •  JUnit searches testCase class for declared methods that follows the rules.