Practice in JUnit for Selenium testing

Keywords: Java Junit Selenium Google

Automated testing helps simplify the lives of software testers by allowing them to automate repetitive tasks, while open source test automation frameworks such as Selenium enable users to automate the Web test experience on a large scale But if you can't verify that the test case passed, what's the use of automated testing?

This is a reflection of the assertion, so you can track how many test failures or successes you encounter after executing the automation script for Selenium tests. Today, I'm going to tell you how to assert in JUnit. Different types of assertions in JUnit are represented by examples.

What is assertion? Why use them?

Assertions, whether placed in selenium testing using tools and frameworks, are an integral part of automated testing. Use assertions in tests to verify or check that the results of actions / functions are the same as expected after the test is performed. In short, they are used to verify the pass or fail state of a test case.

When we run test cases / scenarios that we want to automate, it's important to find out which scenarios pass or fail to understand whether the execution of automated scripts meets expectations.

To do this, we have to provide some kind of assertion, so at the end of the operation, our code will compare and assert in JUnit or any other test automation framework to assess whether the results we get are as expected.

If the actual result is the same as the expected result, you can mark the assertion as passed, if not satisfied, you can mark the assertion as failed.

When all assertions in the test script are satisfied, only one test case is considered passed. You can use the JUnit framework's predefined methods to handle assertions in Selenium Java.

There are two main types of assertions in selenium testing: hard assertions and soft assertions.

  • Hard assertion – if the assertion condition does not match the expected result, a hard assertion is used when we want the test script to stop immediately. Because the assertion condition failed to achieve the expected result, an assertion error will be encountered and the test case being executed will be marked failed.
  • Soft assertion – the execution of the test script does not stop even if the assertion condition is not met. Similarly, in the case of soft assertions, when the assertion conditions will not meet the expected results, no errors will be raised, and the execution of the test script will continue to the next test case step.

That said, it's time to delve into the various assertions in JUnit with examples.

Assertion types for selenium testing in JUnit

The declaration method in JUnit is provided by the class "org.junit.Assert", which extends the "java.lang.Object" class. Now, we'll explore the different methods declared in JUnit with examples.

assertEquals()

The JUnit assertEquals() method compares the equality of the expected result with the actual result. When the expected result we provide does not match the actual result of the Selenium test script after the operation is performed, it raises an assertion error. This causes the execution of the test script to be terminated on the line itself.

Syntax:

Assert.assertEquals(String expected, String actual);
Assert.assertEquals(String message, String expected, String actual);

This is a JUnit assertEquals example to help you better understand the process.

package com.test;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class AssertionDemoClass {


    public static WebDriver driver;
    
    @BeforeClass
    public static void openBrowser()
    {
        System. setProperty("webdriver.chrome.driver", "D:\\AutomationPractice\\chromedriver_win32\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.manage().window().maximize();
    }
    
    @Test
    public void assertURL() {
        // TODO Auto-generated method stub
        driver.get("https://www.lambdatest.com/");
        
        String actualURL = driver.getCurrentUrl();
        System.out.println(actualURL);
        
        Assert.assertEquals("https://www.lambdatest.com/",actualURL);
        System.out.println("Test Passed");
    }
    
    @AfterClass
    public static void closeBrowser()
    {
        driver.close();
    }

}

In the above code, we can see that we provide two parameters in the JUnit assertEquals () method, which are the expected result and the actual result. If the value of the actual URL does not match the expected URL mentioned in the Selenium test script, an assertion error is raised and the execution of the program is terminated on the same line (that is, the assertion statement itself).

We can also pass assertion error messages as parameters, as shown in the syntax.

Assert equals is a floating-point declaration

If we need to compare floating-point types (such as double or float), in this case, to avoid rounding errors, we must provide other parameters that can be called delta.
Incremental values can be evaluated as:

Math.abs (expected - actual) = increment

If there are marginal differences between the expected and actual values due to rounding, these marginal differences can be considered the same and the assertion should be marked as qualified. Therefore, the increment value given by the user determines which margin value should be considered to pass the declaration.

It can be used with float and double data types. Please refer to the following syntax

Syntax:

public static void assertEquals(float expected,float actual,float delta)
public static void assertEquals(double expected,double actual,double delta)

Declare JUnit examples for floating point declarations

@Test
    public void assertURL() {
        // TODO Auto-generated method stub      
        
        double actualDoubleValue= 2.999;
        double expectedDoubleValue = 3.000;
        
        Assert.assertEquals(expectedDoubleValue, actualDoubleValue, 0.001);
        
        System.out.println("Test Passed");      
        
    }

assertTrue()

If you want to pass the parameter value to True for specific conditions invoked in the method, you can use.JUnit assertTrue (). You can use JUnit asserttrue() in two practical situations.

  • Condition is passed to JUnit as a Boolean parameter for assertion by using the assertTrue method. If the condition given in the method is not True, an assertion error (no message) is thrown.

Syntax:

Assert.assertTrue(boolean assertCondition);

  • By passing two parameters in the assertTrue () method at the same time. One parameter is used to assert the error message, and the second parameter is used to specify the specific condition that the assertion method needs to be applied to be True. If the condition given in the method is not True, an AssertionError with a message is thrown.

Syntax:

Assert.assertTrue(String message, boolean assertCondition);

Let's take a look at the assert JUnit sample Selenium test script of assertTrue():

package com.assertions.junit 1;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class AssertionDemo1 {

    public static WebDriver driver;
    
    @BeforeClass
    public static void openBrowser()
    {
        System. setProperty("webdriver.chrome.driver", "D:\\AutomationPractice\\chromedriver_win32\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.manage().window().maximize();
    }
    
    @Test
    public void assertURL() {
        driver.get("https://www.spicejet.com/");
        
        String actualURL = driver.getCurrentUrl();
        System.out.println(actualURL);
        
        String expectedURL="https://www.spicejet.com/";
        
        Assert.assertTrue("URL does not match",expectedURL.equals(actualURL));
        System.out.println("Test Passed");  
        
    }

    
    @AfterClass
    public static void closeBrowser()
    {
        driver.close();
    }
}

In the above code, we can see that two parameters are provided in the assertTrue () method, namely assertion error message and Boolean condition. If the conditions do not match or hold, an assertion error is raised and execution of the program is terminated on the same line, the assertion statement itself.

If we don't want to provide assertion error messages, we just need to provide conditions, as we saw in the syntax above.

assertFalse()

Instead of JUnit assertTrue, we can use the assertFalse() method to verify that the given condition is False. You can also declare JUnit assertFalse in two ways.

  • It takes conditions as parameters and needs to be asserted. If the condition given in the method is not False, an assertion error (no message) is raised.

Syntax:
Assert.assertFalse(boolean condition);

  • Similar to assertTrue, you can pass two parameters for assertFalse. One determines the assertion error message, and the other determines the condition under which assert False is applied. If the condition given in the method is not False, an assertion error with a message is raised.

Syntax:
Assert.assertFalse(String message, boolean condition);

Let's take a look at an assertion JUnit sample Selenium test script of assertFalse():

package com.assertions.junit 1;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class AssertionDemo1 {

    public static WebDriver driver;
    
    @BeforeClass
    public static void openBrowser()
    {
        System. setProperty("webdriver.chrome.driver", "D:\\AutomationPractice\\chromedriver_win32\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.manage().window().maximize();
    }
    
    @Test
    public void assertURL() {
        // TODO Auto-generated method stub
        driver.get("https://www.spicejet.com/");
        
        String actualURL = driver.getCurrentUrl();
        System.out.println(actualURL);
        
        String expectedURL="https://www.google.com/";
        
        Assert.assertFalse("URL does match",expectedURL.equals(actualURL));
        System.out.println("Test Passed");          
    }
    
    @AfterClass
    public static void closeBrowser()
    {
        driver.close();
    }
}

In the Selenium test script above, we can see that two parameters are provided in the assertFalse() method, namely, assertion error message and Boolean condition. If the condition does match or is not false, an assertion error is raised, and execution of the program is terminated at the same line, the assertion statement itself.

If we don't want to provide assertion error messages, we just need to provide conditions, as we saw in the syntax above.

assertNull()

To verify that the passed object contains a null value, we use the assertNull () method, which helps display assertion errors when the object is not a null value.

Syntax:

Assert.assertNull(Object obj);
Assert.assertNull(String msg, Object obj);

Let's take a look at the sample Selenium test script for JUnit assertNull():

package com.assertions.junit 1;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class AssertionDemo1 {

    public static WebDriver driver;
    
    
    //To open the browser before running test
    @BeforeClass
    public static void openBrowser()
    {
        System. setProperty("webdriver.chrome.driver", "D:\\AutomationPractice\\chromedriver_win32\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.manage().window().maximize();
    }
    
    @Test
    public void assertURL() {
        
        //Redirect to the URL 
        driver.get("https://www.spicejet.com/");
        
        String actualURL = driver.getCurrentUrl();
        System.out.println(actualURL);
        
        String expectedURL=null;
        
        //Assertion     
        //Assert.assertNull("Not Null",actualURL);
        //OR
        Assert.assertNull("Not Null",expectedURL);

        System.out.println("Test Passed");  
        
    }
    
    //To close the browser after running test
    @AfterClass
    public static void closeBrowser()
    {
        driver.close();
    }

}

In the above code, we can see that two parameters are provided in the assertNull () method, namely, assertion error message and object. If the supplied object is not null, an assertion error is raised and execution of the program is terminated at the same line, the assertion statement itself.
If we don't want to provide assertion error messages, we can provide an object, as we saw in the above syntax.

assertNotNull()

The assertNotNull() method checks whether the supplied object does not contain a NULL value. We can pass the object as a parameter in this method. If the passed object does contain NULL value and the provided assertion error message, the assertion error will be obtained.

Syntax:

Assert.assertNotNull(Object obj);
Assert.assertNotNull(String msg, Object obj);

Let's take a look at the assert JUnit sample Selenium test script of assertNotNull():

package com.assertions.junit 1;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class AssertionDemo1 {

    public static WebDriver driver;
    
    
    //To open the browser before running test
    @BeforeClass
    public static void openBrowser()
    {
        System. setProperty("webdriver.chrome.driver", "D:\\AutomationPractice\\chromedriver_win32\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.manage().window().maximize();
    }
    
    @Test
    public void assertURL() {
        
        //Redirect to the URL 
        driver.get("https://www.spicejet.com/");
        
        String actualURL = driver.getCurrentUrl();
        System.out.println(actualURL);
        
        String expectedURL="https://www.google.com/";
        
        //Assertion     
        Assert.assertNotNull("Null Object", actualURL);;
        System.out.println("Test Passed");  
        
    }
    
    //To close the browser after running test
    @AfterClass
    public static void closeBrowser()
    {
        driver.close();
    }

}

In the above code, we can see that two parameters are provided in the assertNotNull () method, namely, assertion error message and object. If the supplied object is null, only assertion errors are raised, and execution of the program is terminated at the same line, the assertion statement itself.

If we don't want to provide assertion error messages, we just need to provide an object, as we saw in the above syntax.

assertSame()

When executing Selenium tests, you may often encounter a situation where you need to compare two different objects passed as parameters in a method to assess whether they refer to the same object. Here you can use JUnit assertSame(). If two objects do not reference the same object, an assertion error is displayed. In addition, if an error message is provided, we will receive an assertion error message, as shown in the following syntax.

Syntax of JUnit assertSame() in Selenium test script:

Assert.assertSame(Object expected, Object actual);
Assert.assertSame(String message, Object expected, Object actual);

assertNotSame()

The assertNotSame() method verifies that the two objects passed as parameters are not equal. If two objects have the same reference, an assertion error is raised along with the message we provided, if any.
Another thing to note about this method is that it compares references to objects rather than their values.

Syntax of JUnit assertNotSame() in Selenium test script:

Assert.assertNotSame(Object expected, Object actual);
Assert.assertNotSame(String message, Object expected, Object actual);

assertArrayEquals()

The assertArrayEquals () method verifies that the two arrays of objects we pass as parameters are equal. If the values of both arrays of objects are null, they are considered equal.
If both arrays of objects we pass as parameters in a method are not equal, the method raises a declaration error and provides a message.

Syntax of JUnit assertArrayEquals() in Selenium test script:

Assert.assertArrayEquals(Object[] expected, Object[] actual);
Assert.assertArrayEquals(String message, Object[] expected, Object[] actual);

Differences between JUnit assertions between JUnit 5 and JUnit 4

JUnit Jupiter comes with many assertion methods that already exist in JUnit 4, and it adds more assertion methods to make it suitable for use with Java 8 Lambdas. In JUnit Jupiter, assertions are static methods org.junit.jupiter.api.Assertions in the class

In Junit 4, org.junit.Assert has different assertion methods to verify the expected results and results. Again, we can provide additional parameters for assertion error messages as the FIRST parameter in the method signature. You can refer to them using the following syntax or each of the methods discussed above.

Example:

public static void assertEquals(long expected, long actual);
public static void assertEquals(String message, long expected, long actual);

In JUnit 5, org.junit.jupiter.Assertions contains most of the assert methods, including the other assertThrows () and assertAll () methods.

JUnit 5 assertion methods also have overloaded methods to support the delivery of error messages to be printed in the event of a test failure

Junit 4 Junit 5
The class used is' org. JUnit. Asset ' The class used is' org.junit.jupiter.api.Assertions'
Assertion error message is the first parameter, although it is optional The assertion error message can be passed as the last parameter, which is also optional
New method: None New methods: assertAll() and assertThrows()

A new way to assert JUnit 5

Now we have a clear understanding of the differences in the way JUnit 5 and JUnit 4 are declared. We will now delve into the latest methods declared in JUnit 5.

assertAll()

The newly added method assertAll() is executed to check whether all assertions are group assertions. It has an optional header parameter that allows the method assertAll () to identify a set of assertions. On failure, the assertion error message displays details about each field assertion used in the group.

Let's look at an example of assert JUnit with assert all:

package com.test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;

import java.util.Arrays;
import java.util.List;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class AssertionDemoClass {

    public static WebDriver driver;
    
    @BeforeClass
    public static void openBrowser()
    {
        System. setProperty("webdriver.chrome.driver", "D:\\AutomationPractice\\chromedriver_win32\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.manage().window().maximize();
    }
    
    @Test
    public void assertURL() {
        // TODO Auto-generated method stub
        driver.get("https://www.spicejet.com/");
        
        
        String actualURL = driver.getCurrentUrl();
        System.out.println(actualURL);
        String expectedURL="https://www.spicejet.com/";
            
        String actualTitle =  driver.getTitle();
        System.out.println(actualTitle);
        String expectedTitle = "SpiceJet - Flight Booking for Domestic and International, Cheap Air Tickets";
        
        Assertions.assertAll( 
                () -> assertEquals(expectedURL, actualURL),
                () -> assertEquals(expectedTitle, actualTitle)
                );
        
        System.out.println("Test Passed");
    }
    
    @AfterClass
    public static void closeBrowser()
    {
        driver.close();
    }
}

assertThrows()

Another new addition to JUnit 5 is to replace the ExpectedException Rule in JUnit 4. Now you can make all the declarations for the returned Throwable class instance, which makes the test script more readable. As executables, we can use lambda or method references.

Third party assertions in JUnit

JUnit Jupiter provides enough assertion functions for most test schemes, but there may be some schemes that need additional functions, in addition to the functions provided by JUnit Jupiter, such as the need or need of matchers.

In this case, JUnit team suggests using third-party assertion libraries, such as Hamcrest, AssertJ, Truth, etc. Users can use these third-party libraries when they need to.

In the case of an assertion JUnit example alone, to make assertions more descriptive and readable, we can use a combination of matchers and fluent API s.

The org.junit.jupiter.api.Assertions class of JUnit Jupiter (JUnit 5) does not provide the method assertThat(), which can be used in the org.junit.Assert class of JUnit 4. This method accepts hamtrust matcher. In this way, you can take advantage of the built-in support that third-party assertion libraries provide for matchers.

Sum up

If you want to automate through Selenium testing, assertions play an indispensable role. They help us determine whether a test case passes by evaluating the parameters passed to the object through the Selenium test script.

Selected technical articles

Selected non-technical articles

Great coffee style

Posted by Pests on Thu, 07 Nov 2019 23:17:11 -0800