Вы находитесь на странице: 1из 27

4.

Downloading and installation Of JUnit with Eclipse


How to download and install junit with eclipse step by step
We have already learn how to configure eclipse for webdriver, Creating new
project, new package and then adding new class in my one of the previous
post. In that post you can see how to add external jars of webdriver in
eclipse. Also you can view how to run your first webdriver test in eclipse for
better
understanding.
Generally you do not need to install junit with eclipse if you have already
added external jar files of webdriver with eclipse. Because required jar file
for junit will be already there with webdriver jar files.
How to verify that required jar file for junit is in my build path or not
For junit jar file verification, Right click on your project -> Build Path ->
Configure build path
It will open java build path window as shown in bellow image. In that window,
go to Libraries tab. Here you will see all your jar files. In jar file tree view,
look for the jar file name which is starting with junit.
Java build path window

If this kind of junit jar file is already there then you do not need to install junit
jar with eclipse and you are ready to use junit with eclipse. But if junit jar file
is not there then you need to add it.
Downloading junit jar file
Go to http://junit.org/ website -> Click on download and install guide link will
redirect the page at junit jar file download and install page. Here you will find

the link like "junit.jar". Click on it will redirect to junit jar file downloading
page. From this page download the latest version of junit jar file.
Installing junit jar file with eclipse
Go to java build path window as shown in above figure. Now click on Add
External JARs button to add your downloaded junit jar file with eclipse. After
adding junit jar file, click on OK button to close java build path window.
Now you are ready to use junit with eclipse for your webdriver test of
software application. Click here to view all articles on webdriver.
--5.1 Creating and running webdriver test with junit
Creating and running webdriver test with junit and eclipse step by step
We have already discussed about how to download and install junit in eclipse
to run webdriver test in my previous post. Please note that you need to add
junit jar file only if it is not available in webdriver jar file folder. If it is already
there with webdriver jar file folder then you not need to do anything to
create and run
junit test. Now let me describe you how to create webdriver test case using
junit.
Webdriver test case creation using junit and eclipse
You are already aware about how to create new project and package in
eclipse and if you are not aware then please visit this post page. To
create JUnit Test Case, you need to add JUnit Test Case at place of Class
inside your package. Look at bellow given image to know how to add JUnit
Test Case.

As shown in above image, Select JUnit Test Case from Select a wizard dialog
anf then click on Next button. On Next page, Enter your test case name and
click on Finish button.

When you add JUnit Test Case, your eclipse project explorer window will looks
like bellow given image.

Now replace bellow given code with your original code.


package Testjunit;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Mytest {
WebDriver driver = new FirefoxDriver();
@Test
public void test() {
driver.manage().window().maximize();
System.out.print("Window maximise");
driver.get("http://only-testing-blog.blogspot.in/");
System.out.print("Site Open");
driver.quit();
System.out.print("End of Test");
}
}
Running webdriver test case using junit in eclipse
After replacing above code with your original code, click on Run button in
eclipse. It will show you Run As dialog as shown bellow.

Select JUnit Test from Run As dialog and click on Ok button. Eclipse will run
your test case using JUnit and on completion of execution, you can see your
result in JUnit pane as bellow.

VIEW THIS POST to know how to create and run junit test suite in eclipse.
--5.2 Creating and running junit test suite with webdriver
How To Create And Run JUnit Test Suit For WebDriver Test - Step By Step
If you are planning to perform regression testing of any application using
webdriver then obviously there will be multiple test cases or test classes
under your webdriver project. Example - There are 2 junit test cases under
your project's package. Now if you wants to run both of them then how will
you
do
it?
Simple
and
easy solution is creating JUnit test suite. If your project has more than 2 test
cases then you can create test suite for all those test cases to run all test
cases from one place.

Before creating junit test suite, you must have to read my post about "How
to download and install junit in eclipse" and "How to create and run junit test
in eclipse". Now let me describe you how to create junit test suite in eclipse
for your junit test case.
Step 1 - Create new project and package
Create new project in eclipse with name = junitproject and then add new
package = junitpack under your project. VIEW THIS POST to know how to
create new project and add package in eclipse. Add required external jar files
for selenium webdriver.
Step 2 - Create 1st Test Case
Now create JUnit test case under junitpack package with class name =
junittest1 as bellow. VIEW THIS post to know how to create junit test case in
eclipse.
package junitpack;
import
import
import
import

org.junit.Test;
org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;

public class junittest1 {


WebDriver driver = new FirefoxDriver();
@Test
public void test() throws InterruptedException {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("junittest
1 executed");
Thread.sleep(2000);
System.out.print("junittest1 class is executed");
driver.quit();
}
}
Step 3 - Create 2nd test case
Same way, Create 2nd test class with name = junittest2 under package =
junitpack as bellow.
package junitpack;

import
import
import
import
import
import
import

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

public class junittest2 {


WebDriver driver = new FirefoxDriver();
@Before
public void setup () {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
}
@After
public void aftertest() {
driver.quit();
}
@Test
public void test1() throws InterruptedException{
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("junittest
2 class-test1");
System.out.print("\njunittest2 class-test1 method is executed");
Thread.sleep(2000);
}
@Test
public void test2() throws InterruptedException {
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("junittest
2 class-test2");
Thread.sleep(2000);
System.out.print("\njunittest2 class-test2 method is executed");
}
}
Step 4 - Create test suite for both test cases
Now we have 2 test cases(junittest1.java and junittest2.java) under package
= junitpack.
To create test suite, Right click on junitpack package folder and Go to -> New

-> Other -> Java -> Junit -> Select 'JUnit Test Suite' as shown in bellow
image.

Now click on Next button.On next screen, add junit test suite name
= junittestsuite and select both test cases as shown bellow image and then
click on Finish button.

It will add new test suite class = junittestsuite.java under your package as
bellow.
package junitpack;
import org.junit.runner.RunWith;

import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({ junittest1.class, junittest2.class })
public class junittestsuite {
}
If you see in above suite class, there are 2 junit annotations added with
name = @RunWith and @SuiteClasses. @RunWith annotation will references
junit to run test in class and @SuiteClasses describes classes included in that
test suite.
Now your junit test suite is created and project structure will looks like
bellow.

Step 4 - Running test suite


Select junit test suite class = junittestsuite and run it in eclipse. When you
run junit test suite, eclipse will run both test cases (junittest1 and junittest2)
one by one. When execution completed, you will see bellow given output
lines in console.
junittest1
class
junittest2
class-test1
method
junittest2 class-test2 method is executed

is
is

executed
executed

junit test execution report will looks like bellow.

This way we can create junit test suite to run multiple test cases from one
place. You can view all Junit tutorial posts for webdriver on THIS LINK.
VIEW MY NEXT POST to know how to ignore test from execution.
--6.1 Using JUnit Annotations in webdriver
How to Use JUnit Annotations in webdriver test case with example
Unit testing framework JUnit has many annotations to control the flow and
activity of code execution. You must need to insert JUnit annotation inside
the java code to execute your test case as junit test case. You can look in my
previous post where i have used JUnit @Test annotation before test method.
Let
me
describe
you mostly used 3 JUnit Annotations with example. You can view more details
on JUnit at http://junit.org/.
1. @Before
2. @Test
3. @After
2 other frequently used annotations are @BeforeClass and @AfterClass.
Depending on annotation names, JUnit framework will decide the code
execution flow. i.e. First JUnit framework will execute @Before method,
Second it will execute @Test method and at last it will execute @After
method.
1. @Before Annotation
As name suggest. method written under @Before annotation will be
executed before the method written under @Test annotation. Based on
@Before annotation, JUnit framework will execute that before method first.
Generally method under @Before annotation is used to initializing website
and other environment related setup. @Before annotation method will be

executed before each @Test annotation method means if there are two
@Test methods in your class then @Before method will be executed two
times.
2. @After
Method under @After annotation is known as after method and execution
of @After method will start as soon as completion of @Test method execution
completion. Same as @Before , @After annotation method will be executed
two times if there are two @Test methods in your class.
3. @Test
Method under @Test annotation is known as test method. Execution of @Test
method will start as soon as @Before method execution completed.
Generally we are writing all testing related activity under @Test. We can use
multiple @Test methods in single class too.
4. @BeforeClass
Methods under @BeforeClass annotation will be executed before the any test
method starts execution. It will be executed only once even if there are
multiple @Test
methods
in
your
class.
5. @AfterClass
@AfterClass method will be run on completion of all the test method's
execution from that class. Same as @BeforeClass, @AfterClass method will
be executed once only.
VIEW EXAMPLE OF DIFFERENCE BETWEEN @Before vs @BeforeClass
AND @After VS @AfterClass ANNOTATIONS
Execute bellow given example in your eclipse as a debugging mode to verify
its execution.
package Testjunit;
import java.util.concurrent.TimeUnit;
import
import
import
import
import

org.junit.After;
org.junit.Before;
org.junit.Test;
org.openqa.selenium.*;
org.openqa.selenium.firefox.FirefoxDriver;

public class Mytest {


WebDriver driver = new FirefoxDriver();

@Before
public void beforetest() {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
}
@After
public void aftertest() {
driver.quit();
}
@Test
public void test() {
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.xpath("//input[@value='Bike']")).click();
boolean str1 =
driver.findElement(By.xpath("//input[@value='Bike']")).isSelected();
if(str1 = true) {
System.out.print("Checkbox is checked");
}
else
{
System.out.print("Checkbox is not checked");
}
}
}
Here @After method is written before @Test method but JUnit Framework will
tells eclipse to execute @Test method first and then @After method
--6.2 @Before/@After VS @BeforeClass/@AfterClass Difference
Example Of Difference Between @Before/@After VS
@BeforeClass/@AfterClass In JUnit With WebDriver
Many
readers
are
asking
me
the
difference
between
JUnit
annotations @Before VS @BeforeClass and @After VS @AfterClass in
webdriver test. If you have read my JUNIT ANNOTATIONS POST, I have clearly
described difference between @Before and @BeforeClass annotations and
@After and
@AfterClass annotations in bold text. Now let me describe once more and
then we will look at practical example for both of them.

Difference between @Before and @BeforeClass annotations

Test method marked with @Before annotation will be executed before


the each @Test method. Means if there are 5 @Test methods in your
class then @Before test method will be executed 5 times.

Test method marked with @BeforeClass annotation will be executed


just before the class. Means @BeforeClass method will be executed
only once before the class even if there are 5 @Test methods in your
class.

Difference between @After and @AfterClass annotations

Same
as @Before
annotation, Test
method
marked
@After annotation will be executed after the each @Test method.

@AfterClass annotation will be executed only once after last @Test


method executed.

with

Execute bellow given @Before and @After annotations example in your


eclipse and observe result in console.
package junitpack;
import
import
import
import
import
import
import
import

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

public class junittest2 {


private static WebDriver driver;
@Before
public void openbrowser() {
System.out.print("\nBrowser open");
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");

}
@After
public void closebrowser() {
System.out.print("\nBrowser close");
driver.quit();
}
@Test
public void test1() throws InterruptedException{
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("junittest
2 class-test1");
System.out.print("\njunittest2 class-test1 method is executed");
Thread.sleep(2000);
}
@Test
public void test2() throws InterruptedException {
driver.findElement(By.xpath("//input[@name='fname']")).clear();
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("junittest
2 class-test2");
Thread.sleep(2000);
System.out.print("\njunittest2 class-test2 method is executed");
}
}
When you execute above example in eclipse, Bellow given result will be
displayed in console.
Console Output :
Browser open
junittest2 class-test1 method is executed
Browser close
Browser open
junittest2 class-test2 method is executed
Browser close
Based on above given console output, we can say each @Before method is
executed before each @Test method and each @After method is executed
after each @Test method. Now let we replace @Before annotation
with @BeforeClass and @After annotation with @AfterClass in same example
and then observe result. Replace bellow given @BeforeClass and @AfterClass
part with @Before and @After part in above example as bellow.
@BeforeClass

public static void openbrowser() {


System.out.print("\nBrowser open");
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
}
@AfterClass
public static void closebrowser() {
System.out.print("\nBrowser close");
driver.quit();
}
Now run above example and look at console result. Console result will be as
bellow.
Console Output :
Browser open
junittest2 class-test1 method is executed
junittest2 class-test2 method is executed
Browser close
As per console result, we can say @BeforeClass method is executed once
only. Same way @AfterClass annotation marked method is also executed
once only.
--6.3 Ignoring JUnit Test from execution
How To Ignore Test In WebDriver With JUnit
As described in my PREVIOUS POST, We can create junit test suite to execute
multiple test cases from one place. See example of my previous post.
junittest2 class have two @Test methods. Now If I wants to exclude/Ignore
1st @Test method from execution and wants to execute only 2nd @Test
method then how
can I do It? Ignoring specific test in junit test is very easy.
@Ignore annotation
We can use JUnit's has inbuilt @Ignore annotation before @Test method to
Ignore that specific webdriver test from execution. Let we apply @Ignore
annotation practically in our test and then observe its execution result.
VIEW JUNIT EXAMPLE OF TIMEOUT AND EXPECTED EXCEPTION TEST
My scenario is to ignore 1st @Test method from execution so i need to put
@Ignore annotation in my test before 1st @Test method as bellow.

@Ignore
@Test
public void test1() throws InterruptedException{
}
Here, @Ignore annotation will exclude test1() method from execution.
Copy bellow given Ignoring @Test method(test1()) part with @Ignore
annotation and replace it will @Test method part given on Step 3 (Create 2nd
test case) of THIS EXAMPLE (Note : @Test method part which needs to
replace is marked with pink color in that example post).
//To ignore this @Test method from execution
@Ignore
@Test
public void test1() throws InterruptedException{
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("junittest
2 class-test1");
System.out.print("\njunittest2 class-test1 method is executed");
Thread.sleep(2000);
}
Now when you run full test suite(junittestsuite.java) then on completion of
junit test suite execution, you will get bellow given result in console.
junittest1 class is executed
junittest2 class-test2 method is executed
As per console result, ignored test(test1()) is not executed.
JUnit test execution report will looks like bellow.

This way, Junit's @Ignore annotation will help us to ignore specific test from
execution.
--6.4 Junit Timeout And Expected Exception Test
Example Of Junit Timeout And Expected Exception Test For WebDriver
Sometimes you need to set time out for your webdriver test or you need to
set expected exception condition for your test. Supposing you have written
test for one module and you wants to set timeout for your test. Here timeout
means allowed maximum time to complete full test. Same way, You are
expecting some
exception during your webdriver test execution and that exception is
acceptable.If you are using junit framework for your webdriver test then you
can do it very easily. We have seen example of - how to Ignore specific
webdriver test using junit's @Ignore annotation in THIS POST. Now let me
describe how to write timeout test and exception test in junit with examples.
Timeout Test In JUnit For WebDriver
We can specify timeout time with junit's @Test annotation as shown bellow. It
will allow maximum 2000 milliseconds to complete the execution of test1()
method. After 2000 miliseconds, it will skip remaining execution and test1()
will be marked with error.
@Test(timeout=2000)
public void test1(){
}
Expected Exception Test In JUnit For WebDriver
We can specify expected exception condition with @Test annotation as
bellow. Here my expected exception is null pointer exception so my expected
condition is NullPointerException.class. You can write your expected
exception like IndexOutOfBoundsException.class, ArithmeticException.class,
ect.
@Test(expected = NullPointerException.class)
public void exceptiontest2() {
}
Junit Example Of Timeout And Expected Exception Test
-Go to THIS PAGE
-Copy example given on Step 3 - Create 2nd test case and paste it in your
eclipse.
-Remove all @Test methods from that example and paste bellow given @Test
methods and then run your test class (junittest2.java).
@Test(timeout=2000)
public void test1() throws InterruptedException{

driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("junittest
2 class-test1");
System.out.print("\njunittest2 class-test1 executed before sleep");
Thread.sleep(5000);
System.out.print("\njunittest2 class-test1 executed after sleep");
}
@Test
public void exceptiontest1() {
throw new NullPointerException();
}
@Test(expected = NullPointerException.class)
public void exceptiontest2() {
throw new NullPointerException();
}
On completion of execution, console will show bellow given out put.
Console Output :
Browser open
junittest2 class-test1 executed before sleep
Browser close
JUnit test result looks like bellow.

test1() method is display with error because test was time out after
2000 milisecond as per our condition.

exceptiontest2() pass successfully because we have placed expected


exception condition with it.

exceptiontest1() display with error


any expected exception condition.

because

there

was

not

Day 4 - Generate Test Report Using JUnit

7. Selenium WebDriver Test report Generation using JUnit - 3 Steps

Generate webdriver test report in HTML by running build xml file : Part
-3

We have seen how to configure system and eclipse in configuration


part 1 and configuration part 2 posts to generate webdriver test report.
Now we have a test case and build.xml file in our project tree. Let me
describe you few steps of configuring and running build.xml file in
eclipse. Now follow the bellow given
build.xml file configuration steps to generate HTML report.

Step 1 : Verify build.xml file work space


Open External Tools Configuration dialog as bellow
Right click on Build.xml - > Run As -> External Tools Configuration. It
will open External Tools Configuration dialog as shown bellow.

In Main tab, you need to verify that your current project's build.xml is
selected or not.My current project name is "JUnitReport" so it is correct
for me. If it is of any other project then you need to change it by
clicking on Browse Workspace button.

Step 2 : Set target execution order


Go to the target tab and then set target execution order = build,
ForReport (My Project name), junitreport. If it is not in this order then

you can change it by unchecking and checking and the check box or by
clicking on order button. So now my target execution order will looks
like bellow.

Step 3 : Set Runtime JRE


Go to JRE tab. Here you need to set Runtime JRE = JDK at place of JRE
as shown in bellow image.

If JDK is not display in Separate JRE list then you can add it by
- Click on Installed JREs button. It will open Preferences dialog.
- Click on Add button from Preferences dialog. It will open Add JRE
dialog.

- Select Standard VM from Add JRE dialog and click on next button as
shown in bellow image.

On Next window, Select JDK folder path(Which is located at C:\Program


Files\Java\ in my system) In JRE home field and click on Finish button. It
will add JDK option in Separate JRE drop down.

Now build file configuration is finished and finally you are ready to run
your build.xml file and generate your test report.

Step 4 : Run build.xml

Now you can run build.xml file in 3 ways.


1st way : Run from External Tools Configuration dialog as shown.

2nd way : Run directly from build.xml file

3rd way : Run from Menu icons

Step 5 : View Report


When you run build.xml file, eclipse will run your junit test case and on
completion of execution report file will be generated in your junit folder
which is located in your project folder as bellow.

Open index.html file. It will looks like bellow.

Eclipse And Ant Configuration Steps To Generate webdriver test


execution report using JUnit : Part - 2

Webdriver test result generation is very important and essential part of


automation testing and for that you need to configure your eclipse
accordingly. Before eclipse and ant configuration, you need to
configure your system as described in Part - 1. Now let me describe
you the steps of eclipse configuration to generate web
driver test execution report using JUnit. Perform bellow given steps.

Step 1 : Create new JUnit Test Case


First of all, you need to create JUnit test case in eclipse as described in
JUnit Test Creation Post 1 and Post 2.

Step 2 : Set Ant Home Entries


To set ant home entries,
- Go to eclipse Menu -> Window -> Preferences. It will open eclipse
preference dialog.
- Select Ant -> Runtime from left side preference tree. Now select
Classpath at right side.
- Select 1st class path Ant Home Entries and click on Ant Home button
and select 'apache-ant-1.9.2' folder path and then click on OK as
shown in bellow image.

Step 3 : Set junit.jar path in Blobal Entries of Ant Runtime Preference if


it is not there
As described above, Go to Ant -> Runtime preference settings and
select Global Entries.
Now click on Add External Jars button and select 'junit.jar' located at
eclipse -> plugins -> org.junit_4.11.0.v201303080030 (This folder
name may be different if you have different version of junit) ->
junit.jar. and then click on OK as shown in bellow image.

Step 4 : Generate build.xml for your project


Now you need to generate build.xml for your project. To generate it,
Right click on your project folder and select Export. It will open Export
dialog as shown in bellow image.

Select Ant Buildfiles from export dialog and clicking on Next button will
show you all your projects list. On Next dialog, select your current
project and click on Finish button as shown bellow.

Look in above image. When you will run build.xml file, your test reports
will be saved in JUnit output directory = 'junit' folder. It will be created
automatically in your project folder when you run build.xml file. We will
learn
how
to
run
build.xml
file
in
my
next
post.

When you click on Finish button, build.xml file will be generated inside
your project folder as shown bellow.

View my Next Post to see how to configure and run build.xml file to
generate your test case report in HTML view.

Вам также может понравиться