JUnit Annotations in Selenium
Check out this post on the most common JUnit annotations in Selenium.
Join the DZone community and get the full member experience.
Join For FreeJUnit is a Java-based, open-source framework to help you execute unit testing. JUnit is used primarily to test each and every unit or component of your application, like classes and methods. It helps to write and run repeatable automated tests to ensure your code runs as intended. The framework offers support to Selenium for automation testing for web apps or websites.
This article is my attempt to help you use JUnit annotations in Selenium as a professional tester would. We would be looking at examples of JUnit annotations in Selenium, their order of execution, along with some special JUnit annotations that are used for a specific purpose. We will also be looking into a collective code for executing each example of JUnit annotations in Selenium.
Before we head on to JUnit annotations in Selenium, let us quickly recap the reasons behind JUnit’s popularity among the tester community.
Why JUnit Is So Popular Among Testers?
JUnit, without a doubt, is considered as one of the top Java test frameworks. Below are the pointers behind it.
- It's an open-source framework
- Offers integrations with IDEs such as Eclipse, IntelliJ, etc. so you could test run your code quickly and easily.
- Offers integration with CI/CD tools such as Jenkins, Teamcity, etc. to help you create a sturdy delivery pipeline.
- Offers assertions to help you conveniently compare actual results with the expected results.
- Offers annotations to help you identify the type of test methods.
- Provides a facility to create a test suite that further includes multiple test cases and even other test suites.
- Provides Test Runner to help you easily execute a Test Suite.
- Makes the test code more readable, elegant, and increases the quality.
- Provides JUnit Test Report Generation in HTML format.
What Are JUnit Annotations?
As stated in the pros above, JUnit annotations in Selenium help to identify the type of methods we have defined in our test code. But the question that arises here is: how do we use JUnit annotations in Selenium? What are the keywords that define JUnit annotations in Selenium? When do we use JUnit annotations in Selenium? If you are going through the same questions, then I will help you answer them by the end of this article.
So, basically, annotations are the meta-tags that provides additional information about the methods and classes defined in our code structure.
In order to execute Selenium WebDriver testing with JUnit, it is necessary to add JUnit annotations in our script.
Note: JUnit Annotations would only be accessible in JUnit 4 plus versions and it requires at least JDK 1.5.
Below is the list of every JUnit annotation in Selenium that will be covered in this blog.
Common JUnit Annotations in Selenium
-
@BeforeClass
-
@Before
-
@Test
-
@After
-
@AfterClass
-
@Ignore
JUnit Annotations in Selenium for Specific Purposes
-
@ParameterizedTest
-
@RunWith
-
@RepeatedTest
-
@Parameters
Digging Deeper With Examples of JUnit Annotations in Selenium WebDriver
Now, we look at each annotation one by one, and at the end, I’ll present the entire compiled code representing all annotations along with the console output at the end of this section.
@BeforeClass
This annotation is used to initialize any object that we use in our running test case. Whenever we initialize any object in the BeforeClass
method, it would be invoked only once. The primary purpose of @BeforeClass
JUnit annotation is to execute some statements before all the test cases mentioned in the script.
@BeforeClass
public static void SetUpClass()
{
//Initialization code goes here
System.out.println("This is @BeforeClass annotation");
}
@Before
This annotation is used whenever we want to initialize any object for the time the method is being used. Suppose we have five test cases; the Before
method will be called before each test method for five times. So, it would be invoked every time the test case is executed. This annotation is usually used for setting up the test environment.
@Before
public void SetUp()
{
// Setting up the test environment
System.out.println("This is @Before annotation");
}
@Test
This annotation tells JUnit that the public void method()
to which it is attached can be run as a test case. This annotation includes the test method for an application that you want to test. A single automation test script may comprise numerous test methods in it.
@Test
public void Addition()
{
c= a+b;
assertEquals(15,c);
System.out.println("This is first @Test annotation method= " +c);
}
@Test
public void Multiplication()
{
c=a*b;
assertEquals(50,c);
System.out.println("This is second @Test annotation method= " +c);
}
@After
For whatever we have initialized in the @Before
annotation method, that initialization should be released in the @After
annotation method. So, this annotation is executed every time after each test method. The primary purpose of @After
annotation is to TearDown. TearDown is a process of deleting temporary data. TearDown can also be used to define the default values or to wipe the slate clean of the test environment.
@After
public void TearDown()
{
// Cleaning up the test environment
c= null;
System.out.println("This is @After annotation");
}
@AfterClass
Whatever we have initialized in the @BeforeClass
annotation method, that initialization should be released in the @AfterClass
annotation method. So, this annotation is executed once, but it will be executed after all tests have finished executing.
@AfterClass
public static void TearDownClass()
{
//Release your resources here
System.out.println("This is @AfterClass annotation");
}
@Ignore
This annotation tells JUnit that this method shall not be executed. In scenarios where our code module is not ready in a particular test case, we can temporarily put that code module in @Ignore
annotation method to avoid test case failure. Native JUnit 4 offers powerful reporting to help you realize the count of tests that were ignored along with the count of tests that run and count of tests that failed.
@Ignore
public void IgnoreMessage()
{
String info = "JUnit Annotation Blog" ;
assertEquals(info,"JUnit Annotation Blog");
System.out.println("This is @Ignore annotation");
}
Here is the compiled code with output representing all the JUnits annotations in Selenium WebDriver:
package JUnitAnnotationBlog;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
public class JUnitAnnotations {
int a=10;
int b=5;
Object c;
@BeforeClass
public static void SetUpClass()
{
//Initialization code goes here
System.out.println("This is @BeforeClass annotation");
}
@Before
public void SetUp()
{
// Setting up the test environment
System.out.println("This is @Before annotation");
}
@Test
public void Addition()
{
c= a+b;
assertEquals(15,c);
System.out.println("This is first @Test annotation method= " +c);
}
@Test
public void Multiplication()
{
c=a*b;
assertEquals(50,c);
System.out.println("This is second @Test annotation method= " +c);
}
@After
public void TearDown()
{
// Cleaning up the test environment
c= null;
System.out.println("This is @After annotation");
}
@AfterClass
public static void TearDownClass()
{
//Release your resources here
System.out.println("This is @AfterClass annotation");
}
@Ignore
public void IgnoreMessage()
{
String info = "JUnit Annotation Blog" ;
assertEquals(info,"JUnit Annotation Blog");
System.out.println("This is @Ignore annotation");
}
}
Console Output of JUnit Annotations in Selenium WebDriver
Execution Sequence of JUnit Annotations for Selenium
Here is a basic process flowchart of JUnit annotations that will help you understand the flow, step by step.
Annotations in JUnit for Specific Purposes
In earlier sections, we covered the most basic JUnit annotations in Selenium. Now, I will show you some advanced JUnit annotations along with their specific purpose.
@ParameterizedTest
This annotation is somewhat similar to @Test
annotation; the difference is that it is used to identify the parameterized test methods. We can also make use of @ValueSource
annotation for providing the method parameters after annotating the test method. Keep in mind that the data type for parameters could be of any type, such as String
or Integer
.
In the below sample code, the variable data
of String type passed as a parameter takes an argument from the source annotation.
The primary purpose of this annotation is to run a test multiple times with different arguments.
Note: Add the below libraries before using these annotation
org.junit.jupiter.params.ParameterizedTest
org.junit.jupiter.params.provider.ValueSource
Example:
@ParameterizedTest
@ValueSource(strings = {"LambdaTest", "JUnit", "Annotations", "Blog"})
void ExampleCode(String data)
{
assertNotNull(data);
}
Output:
@RepeatedTest
This annotation, which has been introduced in JUnit 5, is used to run the test method several times, as per the requirement. The number of repetitions that you want a test to go under can be passed as a parameter to the @RepeatedTest
annotation.
Example
@Test
@RepeatedTest(5)
public void Addition() {
int a=10;
int b=5;
Object c;
c= a+b;
assertEquals(15,c);
System.out.println("This is @RepeatedTest annotation method= " +c);
}
Output
@RunWith
When a class is annotated with the @RunWith
annotation, JUnit invokes the class that is annotated to execute the test. This annotation basically runs with the @SuiteClasses
annotation. This specifies the group of classes to be executed. Each class in a suite executes after the execution of prior running class.
Note: It is necessary to add org.junit.runner.RunWith library in order to use this annotation.
Example
@RunWith(Suite.class)
@Suite.SuiteClasses({
TestSample1.class,
TestSample2.class,
TestSample3.class,
TestSample4.class,
TestSample5.class,
})
public class JunitTest {
// This class remains empty, it is used only as a holder for the above annotations.
}
@Parameters
Note: Do not get confused between the @ParameterizedTest
annotation and @Parameters
annotation. @Parameters
annotation requires the @RunWith
annotation to specify that the test would run with the parameterized runner. However, in @ParameterizedTest
annotations, @ValueSource
would be used as a source annotation to pass arguments.
While using the @Parameters
annotation, we use the @RunWith
annotation to specify that the test will run with the parameterized runner. The runner looks for a method that initializes the test, provides values for the test, and executes the test.
In the below code, the value-set is defined as list Object
arrays, which are annotated with @Parameters
. A parameterized test is a common test that is executed again and again using test parameters. This saves a lot of time for developers in executing the same test with different input types.
Example
@RunWith(Parameterized.class)
public class Blog1 {
String name, password;
@Parameters
public Object[][]
getData()
{
Object[][]
info = {{"ramit1","ramitd11"},
{"ramit2","ramitd22"}};
return info;
}
public Blog1(String id, String pass)
{
this.name = id;
this.password= pass;
}
@Test
public void Sample()
{
SampleCode.login(name, password);
}
}
Below is the code for the SampleCode
class used in the above example:
public class SampleCode {
public static void login(String name, String password)
{ System.out.println(“Login credentials are ” + name + password ) ;
}
}
Output
Attributes Used With JUnit Annotations in Selenium WebDriver
These test annotations in JUnit have multiple attributes that can be used for our test method:
1) timeout – To specify timeout for each test case, the timeout attribute is specified within the @Test
annotation. Timeout time is specified in milliseconds. For example, suppose you know your particular test case takes around 15-20 seconds to get executed, and you want your test to fail if it takes more than 20 seconds to get executed, then you can use this attribute as @Test(timeout=20000)
for your particular test case. If the execution fails, then the progress bar would get red instead of green.
Example
@Test(timeout=10000)
public void ExampleCode()
throws InterruptedException
{
System.setProperty("webdriver.chrome.driver","C:\\Users\\Lenovo-I7\\Desktop\\Selenium\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.lambdatest.com");
driver.manage().window().maximize();
driver.findElement(By.xpath("//*[@id=\'bs-example-navbar-collapse-1\']/ul/li[6]/a")).click();
Thread.sleep(2000);
//Login Page Button
driver.findElement(By.xpath("//*[@id='app']/section/form/div/div/input[1]")).sendKeys("ramit@lambdatest.com");
//Username
driver.findElement(By.xpath("//*[@id=\'app\']/section/form/div/div/input[2]")).sendKeys("Hello1234");
Thread.sleep(2000);
//Password
driver.quit();
}
Now, if you want to put this same timeout for multiple test cases, it is not necessary to add timeout attribute within each and every @Test
annotation you have specified in your script. In such a case, you can use the @Rule
annotation to define a global timeout that would be applicable for each @Test
method annotation of your script.
Example
@Rule
public Timeout
globalTimeout = Timeout.seconds(10);
// 10 seconds max per test method
2) expected – This is a special feature introduced by JUnit 4 that provides the facility to trace an exception that was expected from the execution of a particular code. There are different kinds of exceptions that are probably expected while running code, such as NoSuchMethodException
, ArithmeticException
, IndexOutOfBoundsExceptions
, etc. For example, you expect the occurrence of exception from your code when a particular number is divided by zero. In this case, you would be using ArithmeticException
. If the excepted exception does not occur, then the test execution will fail.
Example
@Test(expected= ArithmeticException.class)
public void ExampleCode()
{
int a= 10,b=0,c;
c=a/b;
System.out.println("Value= " +c);
}
Summarizing It All!
JUnit annotations are a very powerful feature of JUnit and help to improve code structure by making JUnit tests easier and more readable. The use of these annotations totally depends on your project requirement, using an appropriate annotation at the correct place would be very helpful for developers as well as for other team members.
Remember, JUnit annotations for Selenium would only work in JUnit 4 plus versions and would also require to import this particular library: “org.junit.”
Happy testing!
Published at DZone with permission of Ramit Dhamija. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments