Selenium – Introduction to JUnit Framework and Its Usage

By Vijay

By Vijay

I'm Vijay, and I've been working on this blog for the past 20+ years! I’ve been in the IT industry for more than 20 years now. I completed my graduation in B.E. Computer Science from a reputed Pune university and then started my career in…

Learn about our editorial policies.
Updated May 9, 2025

This tutorial will give an insight into JUnit and its usage in selenium script. This is tutorial #11 in our comprehensive Selenium tutorials series.

JUnit is an open-source unit testing tool used to test small/large units of code. To run the JUnit test, you don’t have to create a class object or define the main method. JUnit provides an assertion library that is used to evaluate the test result.

Annotations of JUnit are used to run the test method. JUnit is also used to run the Automation suite having multiple test cases.

Usage of JUnit in Selenium Scripts

Introduction to JUnit Framework

Adding JUnit Library in Java Project

First, we will learn how to add a JUnit library to your Java project:

Step #1: Right click on Java project->Build Path->Configure Build path

Step #2: Click Libraries->Add Library

Add Library

Step #3: Click on JUnit.

Junit framework

Step #4: Select JUnit4-> Finish

Junit library

Step #5: Click OK.

Java build path

Many frameworks, like Data Driven Framework, Keyword Driven Framework, and Hybrid Framework, use the JUnit tool as a test runner and will help start the batch execution and reporting.

JUnit Annotations Used in Selenium scripts

There are many annotations available in Junit. Here we have described a few annotations frequently used in Selenium scripts and frameworks.

#1) @Test

@Test annotation is used to run a Junit test.

Example:

@Test
public void junitTest()
{
System.out.println("Running Junit test");
Assert.assertEquals(1,1);
}

How to Run a JUnit test:

Navigate to run ->Run as JUnit test

#2) @Before

@Before annotation is used to run any specific test before each test.

public class Junttest {
@Before
public void beforeTest(){
System.out.println("Running before test");
}
 
@Test
public void junitTest(){
System.out.println("Running Junit test");
}
}

Output:
Running before test
Running Junit test

Example of before annotation using two JUnit test methods.

public class Junttest {
@Before
public void beforeTest(){
System.out.println("Running before test");
}
 
@Test
public void junitTest(){
System.out.println("Running Junit test");
}
 
@Test
public void secondJunitTest(){
System.out.println("Running second Junit test");
}
}

Output:
Running before test
Running JUnit test
Running before test
Running the second JUnit test

Before running the JUnit test method beforeTest method will run. Similarly, before running the secondJuntiTest again beforeTest method will run and produce output like the above.

#3) @BeforeClass

This method executes once before running all tests. The method has to be a static method. Initialization of properties files, databases, etc is done in the beforeClass method.

public class Junttest {
@BeforeClass
public static void beforeClassTest(){
System.out.println("Executed before class method");
}
 
@Test
public void junitTest(){
System.out.println("Running Junit test");
}
 
@Test
public void secondJunitTest(){
System.out.println("Running second Junit test");
}
}

Output:
Executed before the class method
Running JUnit test
Running the second JUnit test

#4) @After

This method executes after each test.

public class Junttest {
@Test
public void junitTest(){
System.out.println("Running Junit test");
}
 
@After
public void afterTest(){
System.out.println("Running after method");
}
}

Output:
Running JUnit test
Running after method

#5) @AfterClass

Like @BeforeClass, @AfterClass executes once after executing all test methods. Like a @BeforeClass method, the @AfterClass method has to be a static method.

public class Junttest {
 
@Test
public void junitTest(){
System.out.println("Running Junit test");
}
 
@Test
public void secondJunitTest(){
System.out.println("Running second Junit test");
}
 
@AfterClass
Public static void afterClassTest(){
System.out.println("Running afterclass method");
}
}

Output:
Running JUnit test
Running the second JUnit test
Running after-class method

JUnit assertions are used to validate certain conditions and stop the execution of the program if the conditions are not satisfied.

#6) Parameterized JUnit class

A parameterized class is used to run the same scenario with multiple datasets.

Below is an example to pass multiple parameters in a JUnit test.

@Parameters annotation tag is used to pass multiple data. Here, we have taken 2*2 dimensional array and the data can be visualized below:

Junit framework Selenium script 5
@RunWith(Parameterized.class)
public class Junttest {
public String name;
public int age;
public Junttest(String name,int age){
this.name=name;
this.age=age;
}
 
@Test
public void testMethod(){
System.out.println("Name is: "+name +" and age is: "+age);
}
 
@Parameters
public static Collection<Object[]> parameter(){
Object[][] pData=new Object[2][2];
pData[0][0]="Tom";
pData[0][1]=30;
pData[1][0]="Harry";
pData[1][1]=40;
return Arrays.asList(pData);
}
}

JUnit Assertions

JUnit assertEquals: This checks if the two values are equal and assertion fails if both values are not equal.

This compares Boolean, int, String, float, long, char, etc.

Syntax:
Assert.assertEqual(“excepted value”, ”actual value”);

Example:
Assert.assertEqual(“ABC”,”ABC”); //Both the strings are equal and assertion will pass.
Assert.assertEqual(“ABC”,”DEF”); //Assertion will fail as both the strings are not equal.
Assert.assertEqual(“Strings are not equal”, “ABC”,”DEF”); //message will be thrown if the equal condition is not satisfied.

Below is an example of the use of JUnit assertion in selenium:

String username=driver.findElement(By.id(“username”)).getText();
String password=driver.findElement(By.id(“password”)).getText();
Assert.assertEqual(“Mismatch in both the string”, username, password);

In the above example, the assertion will fail as both strings are not equal. One is the text of the username field and the other is the text of the password field.

JUnit assertTrue: Returns true if the condition is true and assertion fails if the condition is false.
Assert.assertTrue(“message”, condition);
Assert.assertTrue(“Both the strings are not equal”, (“HelloWorld”).equals(“HelloWorld”));

Here assertion will pass as both the strings match. It will print the message if the assertion fails.

JUnit assertFalse: Returns true if the condition is false and assertion fails if the condition is true.
Assert.assertFalse(“message”, condition);
Assert.assertFalse(“Both the strings are equal”, (“Hello”).equals(“HelloWorld”));

There will not be any assertion error as the condition is false.

Conclusion

Most of the programmers use JUnit, as it is easy and does not take much effort to test. A simple green or red bar will show the actual result of the test. Junit makes life easy as it has its own set of libraries and annotations. Here we have also described commonly used annotations used with selenium scripts and framework.

More details about the framework and use of JUnit annotations will be discussed in the upcoming tutorial, which is dedicated exclusively to framework design using Junit. This tutorial will help us in designing the framework using Junit.

Next Tutorial #12: In the next tutorial, we will discuss all about TestNG, its features, and its applications. TestNG is an advanced framework designed in a way to leverage the benefits of both the developers and testers.

Was this helpful?

Thanks for your feedback!

Recommended Reading

  • TestNG Testing Framework

    This TestNG Tutorial Explains the TestNG Framework Along with its Features, Benefits, and Advantages Over the JUnit Framework: This tutorial will introduce you to the concept of Automation Framework, its benefits, and the types that are in use in the testing world. Along with the Automation Framework, we will also…

  • Hybrid Driven Framework In Selenium

    This Informative Tutorial Explains What a Hybrid Framework, the Uses and Components of Selenium Hybrid Driven Framework, and How to Implement it is: What is a Hybrid Framework? Hybrid Driven Framework is a combination of both the Data-Driven and Keyword-Driven framework. Here, the keywords, as well as the test data, are externalized.…

  • Keyword Driven Framework In Selenium

    This Comprehensive Tutorial on Keyword Driven Framework Explains Various Components of the Framework & How to Create One in Selenium: In general, Framework is a set of guidelines, which when followed will give beneficial results. The Keyword-Driven framework is a technique to externalize keywords/actions that are used in the script…

  • Data Driven Framework in Selenium using Apache POI

    How to work on Data Driven Framework in Selenium Using Apache POI? Data Driven Framework is one of the most popular Automation Testing Frameworks in the current market. Data Driven automated testing is a method in which the test data set is created in the excel sheet, and is then…


READ MORE FROM THIS SERIES:



21 thoughts on “Selenium – Introduction to JUnit Framework and Its Usage”

  1. hello all,
    really very helpful website.
    can you please explain bit more “#6. Parameterized Junit class”.
    not understand clearly.

    Reply
  2. Please share some more details for the parametrised class used. Though we are able to implement it,

    But it would be great if you can share more details.

    Small typo are
    Assert.assertEqual –> should be Equals (s is missing)
    Assert.assertEqual(“excepted value”, ”actual value”);

    Reply
  3. Hi All ,
    I Ran Jnuit frame frame is working.but i have one small doubt how to pass the import the parameters Excel file in to junit.

    Reply
    • In JUnit4, it can be done as follows:
      1. Declare @FixMethodOrder(MethodSorters.NAME_ASCENDING) before your test class.
      2. For every test method name, prepend some string which will sort in the ASCENDING manner.
      e.g.
      @Test
      public void firstMethod() {
      }

      @Test
      public void secondMethod() {
      }

      Rename methods like:
      @Test
      public void test1_firstMethod() {
      }

      @Test
      public void test2_secondMethod() {
      }

      Reply
  4. The test is wrong with the parameterized.class.. you cant pass an object array into a string and int.. It will fail. the type has to be the same. Either int and int.. or string and string.

    Reply
  5. Hi Shruti, I have two questions:

    1. Whenever I am running the @BeforeClass annotation, the second junit class runs before the first class.
    Instead of this :

    Executed before class method
    Running Junit test
    Running second Junit test

    I get this :

    Executed before class method
    Running second Junit test
    Running Junit test

    Why did it happen?

    Secondly, I am getting an initialization error if I run the parameterized example.

    Reply
  6. @RunWith(Parameterized.class) = showing error here
    Multiple markers at this line
    – Type mismatch: cannot convert from Class to Class

    When tried to run
    Initilizationerror
    java.lang.Exception: Custom runner class Parameterized should have a public constructor with signature Parameterized(Class testClass)
    at org.junit.runners.model.InitializationError.(InitializationError.java:38)
    at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:111)
    at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:84)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:70)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:43)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:444)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

    Could you please tell us how to resolve this

    Reply
  7. @Rahul :
    Answer for your first question:
    The results are displayed randomly, if you want the results to appear as you want it, then user the “priority”
    eg:
    public class Junttest {

    @BeforeClass
    public static void beforeClassTest(){
    System.out.println(“Executed before class method”);

    }

    @Test(priority=1)
    public void junitTest(){
    System.out.println(“Running Junit test”);

    }

    @Test(priority=2)
    public void secondJunitTest(){
    System.out.println(“Running second Junit test”);

    }

    }

    In the above eg, the output would be :
    Executed before class method
    Running Junit test
    Running second Junit test

    Reply
  8. Thank you for the tutorial. It helps me a lot.
    I ran the JunitTest and got the result like this:
    Running before test
    Running second Junit test
    Running before test
    Running Junit test

    Reply
  9. I am new to selenium and followed all the tutorials till chapter 10 with ease. But NOT able to understand this tutorial chapter11. I did the add library part. NOt sure about next steps as it is not clear and you have direclty started Annotations with no information about if it needs to be added to new program or the programs you have described in previous chapters. It would have been nice if you could provide complete program (with import required ) for the program and all in this tutorial. I am getting error while I m trying the above. Please help

    Reply

Leave a Comment