DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Top 7 Cross Browser Testing Tools in 2021
  • Difference Between Cross-Browser Testing and Responsive Testing
  • How to Quickly Build a Progressive Web App Using Lightning Web Components
  • 6 of the Best API Testing Tools in the Market

Trending

  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • Concourse CI/CD Pipeline: Webhook Triggers
  • Blue Skies Ahead: An AI Case Study on LLM Use for a Graph Theory Related Application
  • DGS GraphQL and Spring Boot
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Automated Testing With JUnit and Selenium for Browser Compatibility

Automated Testing With JUnit and Selenium for Browser Compatibility

Learn how to implement automated testing with JUnit and Selenium for enhanced browser compatibility.

By 
Sadhvi Singh user avatar
Sadhvi Singh
·
Feb. 01, 19 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
41.6K Views

Join the DZone community and get the full member experience.

Join For Free

Cross-browser testing is a process by where you test your website over multiple browsers and browser versions running on different operating systems. This is done to realize the cross-browser compatibility of a website or a web app when accessed across a variety of browsers. If your web app isn’t cross-browser compatible, then not only would you be missing out on potential leads but your customer retention could also suffer. These browser differences could be anything from layout to typography, and these cross-browser differences happen as each browser has a unique rendering engine, which is responsible for rendering web elements.

However, cross-browser testing can be highly time-consuming if executed manually. Think about how many browser versions you would need to encounter from legacy to modern and the surplus variety of browsers available in the market. You also would have to consider specific browsers offered by specific mobile vending companies. There are ways you could fast track your manual cross-browser testing effort, and automation testing sits on top of the list for saving everyday time and effort.

This article references automation testing with JUnit and Selenium for a web application through a simple script.

JUnit is an open-source unit testing tool that helps to test units of code. It is mainly used for unit testing Java projects; however, it can be used with Selenium Webdriver to automate the testing of web applications. So, you can even perform automation testing of a web application with JUnit. To be precise, JUnit is a unit testing framework for Java that helps to write test cases in a more structured format. Selenium and JUnit can be used independently of each other, though, testing with JUnit and Selenium combined helps to write test cases in a more structured way. We will be walking through the following topics for automating test scripts for web application testing with JUnit and Selenium:

  • Downloading JUnit Jars
  • Adding Jars to your Selenium project
  • Incorporating JUnit annotations and methods into your first Selenium scripts
  • Cloud testing with JUnit and Selenium Using LambdaTest

Step 1. Downloading JUnit Jars

JUnit jar files can be downloaded from https://github.com/JUnit-team/JUnit4/wiki/Download-and-Install. The major jar files included are:

  • junit.jar
  • hamcrest-core.jar

Download and save these files in your system.

Step 2. Adding Jars to Your Selenium Project

In order to add your JUnit external jar files into your project, you need to have an advanced code editor/compiler tool of your preference. I usually work with Eclipse, so I would be narrating using the same. You also need to have Selenium jar files downloaded. In order to install Eclipse, you can refer to its official website. Based on your operating system windows or OS, you can download accordingly. Post Eclipse setup, you can download your Selenium jar files from its official website. In order to create your Selenium WebDriver scripts, you need to use user language-specific drivers. In our case, we are using Java, though Selenium grid supports multiple languages like C#, Ruby, Python, and Javascript, along with Java. Download the Selenium jar files and include them into your code editor/compiler workspace, now for automating test script for testing with JUnit and Selenium grid, we need to include our downloaded JUnit Jar files. Follow the below steps to do so:

  • Right click on your created project and select properties:JUnit
  • Click on Java build path from the options:Java-Build-Path
  • Click on the ‘Add external Jars’ button and add your downloaded JUnit Jar files and click ‘OK’ post that:

This adds the JUnit jar files to your Selenium project. The major class file/source files that are commonly used in this JUnit Jar files are:

  • Assertions
  • Annotations
  • Parameterized
  • Ignore
  • TestListeners, etc.

For detail list on the class files or source files, refer here. Now, let us incorporate JUnit into your Selenium project for proceeding web application testing with JUnit and Selenium.

Step 3. Incorporating JUnit to Your Selenium Script

The first block for building collaboration in this article, for testing with JUnit and Selenium for a web application, would be to create our first JUnit Selenium simple script on https://www.lambdatest.com/.

Reference Code:

import static org.junit.Assert.*; 
import java.util.concurrent.TimeUnit; 
import org.junit.AfterClass; 
import org.junit.BeforeClass; 
import org.junit.Test; 
import org.openqa.selenium.By; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.chrome.ChromeDriver;       
public class Lamdatest_Junit {   
static WebDriver driver; 
@BeforeClass public static void BrowserOpen() 
{ System.setProperty("webdriver.chrome.driver", "path of your chromedriver");     
driver= new ChromeDriver() ;     
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); } 
@Test public void Register_User() { driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); 
driver.get("https://www.lambdatest.com/ "); 
driver.manage().window().maximize(); 
driver.findElement(By.xpath("//a[text()='Free Sign Up']")).click(); 
driver.findElement(By.xpath("//input[@name='organization']")).sendKeys("LambdaTest"); 
driver.findElement(By.xpath("//input[@name='first_name']")).sendKeys("Test"); 
driver.findElement(By.xpath("//input[@name='last_name']")).sendKeys("User"); 
driver.findElement(By.xpath("//input[@name='email']")).sendKeys("User2@gmail.com"); 
driver.findElement(By.xpath("//input[@name='password']")).sendKeys("TestUser123"); 
driver.findElement(By.xpath("//input[@name='phone']")).sendKeys("9412262090"); 
driver.findElement(By.xpath("//button[text()='SIGN UP']")).click(); 
String url= driver.getCurrentUrl(); assertEquals("fail- unable to register", url, "https://accounts.lambdatest.com/user/email-verification"); } 
@AfterClass public static void BrowserClose() { driver.quit(); }   }


Details:

The above script opens the browser with https://www.lambdatest.com/ and clicks on ‘free sign up’ button to register. Post register, the script will check the URL it is redirected to in order to ensure a successful registration. We have used two classes of JUnit one is Annotations class and the other Assertions.

The script consists of three sections:

  • @BeforeClass – This annotation runs the piece of code before starting any annotation in the class. As you can see here, we have opened the chrome browser before performing any action on it. The main actions are performed in the @Test annotation marked method.
  • @Test – This test method carries the functionality where the application is opened and the registration process is carried out. To validate the result, we have used assertion class where we are validating the success of the registration process using the context of current URL. This test annotation runs the piece of code after the @BeforeClass and @BeforeTest method and before the @AfterTest and @AfterClass method.
  • @AfterClass — This annotation tells JUnit to run the piece of code once all the tests have been executed. This annotation method usually carries the process of closing the browser post all action items have been performed.
  • Attaching video of the execution of the above script:

    So far, you have seen how to automate your web app testing with JUnit and Selenium using a local WebDriver instance. However, there is a downside to that. You can only invoke the automated cross-browser testing over the browsers that are installed in your machine. Plus, you need to have your machine every time that you aim for running automation testing with JUnit and Selenium for a web app. It is why testing on the cloud is emerging as a dominant preference worldwide. LambdaTest is a cloud-based, cross-browser testing tool that offers supports with Selenium grid, providing a solution to every obstacle you face while performing automation testing using your local machine. LambdaTest offers a Selenium grid consisting 2000+ browsers for you to perform automation testing effortlessly.

    Let me demonstrate how you could easily perform automation testing using LambdaTest.

    To run your test suite on our Selenium grid, you have to configure a couple of capabilities so that your tests execute on a remote browser. Refer to our Capability Generator Tool to help you fetch your desired capabilities at ease.

 2WebDriver driver = new RemoteWebDriver(new URL("https://" + username + ":" + accesskey + "@hub.lambdatest.com/wd/hub"), DesiredCapabilities.firefox());


  • Now, let’s start with a simple Selenium WebDriver test. Below is a JUnit Selenium script that will open a sample to-do application which will do the following task:

    1. Mark first two items as mark done.
    2. Add a new item to the list.
    3. Return the added item.

  • import org.junit.After; 
    import org.junit.Before; 
    import org.junit.Test; 
    import org.junit.runner.RunWith; 
    import org.openqa.selenium.JavascriptExecutor; 
    import org.openqa.selenium.WebDriver; 
    import org.openqa.selenium.remote.CapabilityType; 
    import org.openqa.selenium.remote.DesiredCapabilities; 
    import org.openqa.selenium.remote.RemoteWebDriver; 
    import java.net.URL; public class JUnitTodo {      public String username = "YOUR_USERNAME";     
    public String authkey = "YOUR_ACCESS_KEY";     public static RemoteWebDriver driver = null;     
    public String gridURL = "@hub.lambdatest.com/wd/hub";     
    boolean status = false;        
    @Before     public void setUp() throws Exception {        
    DesiredCapabilities capabilities = new DesiredCapabilities();         
    capabilities.setCapability("browserName", "chrome");         
    capabilities.setCapability("version", "70.0");         
    capabilities.setCapability("platform", "win10"); // If this cap isn't specified, it will just get the any available one         
    capabilities.setCapability("build", "LambdaTestSampleApp");         
    capabilities.setCapability("name", "LambdaTestJavaSample");         
    capabilities.setCapability("network", true); // To enable network logs         
    capabilities.setCapability("visual", true); // To enable step by step screenshot         
    capabilities.setCapability("video", true); // To enable video recording         
    capabilities.setCapability("console", true); // To capture console logs         
    try {             driver = new RemoteWebDriver(new URL("https://" + username + ":" + accesskey + gridURL), capabilities);         
    } catch (MalformedURLException e) {             System.out.println("Invalid grid URL");
    } catch (Exception e) {             System.out.println(e.getMessage());
    }     }        
    @Test     public void testSimple() throws Exception {        
    try {  //Change it to production page
    
    driver.get("https://4dvanceboy.github.io/lambdatest/lambdasampleapp.html"); //Let's mark done first two items in the list.               
    driver.findElement(By.name("li1")).click();             
    driver.findElement(By.name("li2")).click();// Let's add an item in the list.               
    driver.findElement(By.id("sampletodotext")).sendKeys("Yey, Let's add it to list");             
    driver.findElement(By.id("addbutton")).click();   // Let's check that the item we added is added in the list.             
    String enteredText = driver.findElementByXPath("/html/body/div/div/div/ul/li[6]/span").getText();            
     if (enteredText.equals("Yey, Let's add it to list")) {                 
    status = true;             
    }         
    } catch (Exception e) {             
    System.out.println(e.getMessage());         
    }     }        
    @After     
    public void tearDown() throws Exception {        
    if (driver != null) {             
    ((JavascriptExecutor) driver).executeScript("lambda-status=" + status); // relay whether the test has passed or failed as marked by the user             
    driver.quit();         
    }     } }


    You could also test your local files through LambdaTest Selenium grid for performing automation testing of a web application with JUnit and Selenium. You can do with the help of advanced capabilities provided by LambdaTest Capabilities Generator. These advanced capabilities will help you to:

    • Perform the test on your locally hosted web pages.
    • Generate browser console logs for every step executed through your test.
    • Configure a custom time zone for executing your test.
    • Generate network logs through your test execution.
  • If we want to activate all of the above-mentioned advanced capabilities, then you need to add the below desired capabilities:


DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(“tunnel”,true); // allows you to run tests for your locally hosted web pages.
capabilities.setCapability(“console”,true); // generates console logs
capabilities.setCapability(“network”,true); // generates network logs
capabilities.setCapability(“timezone”,”UTC+12″); //considering you want your test to run on the time zone UTC+12.

  • Parallel Testing

    LambdaTest also provides the ability to perform parallel test execution. With LambdaTest parallel testing, you could run a similar test across multiple browsers, simultaneously. This helps to bring down the time taken on test build activities, significantly. Here is an example of parallel testing performed to automate web application testing with JUnit and Selenium using LambdaTest.

    To run a test on different browsers at the same time, you will need to create a helper class that extends the paramerterized class (org.junit.runners.Parameterized) and implements the RunnerScheduler class.

    (org.junit.runners.model.RunnerScheduler) to support JUnit tests in parallel. See the example below:

import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 
import java.util.concurrent.TimeUnit; 
import org.junit.runners.Parameterized; 
import org.junit.runners.model.RunnerScheduler; 
public class Parallelized extends Parameterized {     
private static class ThreadPoolScheduler implements RunnerScheduler {         
private ExecutorService executor;         
public ThreadPoolScheduler() {             
String threads = System.getProperty("junit.parallel.threads", "15");             
int numThreads = Integer.parseInt(threads);             
executor = Executors.newFixedThreadPool(numThreads);         }         
@Override         
public void finished() {             
executor.shutdown();             
try {                 
executor.awaitTermination(10, TimeUnit.MINUTES);             
} catch (InterruptedException exc) {                
throw new RuntimeException(exc);             }         }         
@Override         
public void schedule(Runnable childStatement) {             
executor.submit(childStatement);         
}     }     
public Parallelized(Class<?> klass) throws Throwable {         
super(klass);         
setScheduler(new ThreadPoolScheduler());     } }


  • Here is an example of JUnit Test; this would be representing the helper class used above for executing the parallel testing.

import org.openqa.selenium.By; 
import org.openqa.selenium.Platform; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.remote.DesiredCapabilities; 
import org.openqa.selenium.remote.RemoteWebDriver; 
import org.junit.After; import org.junit.Before; 
import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.junit.runners.Parameterized; 
import java.net.MalformedURLException; 
import java.net.URL; 
import java.util.LinkedList; 
@RunWith(Parallelized.class) public class JUnitConcurrentTodo {      
public String username = "YOUR_USERNAME";     
public String accesskey = "YOUR_ACCESS_KEY";     
public String gridURL = "@hub.lambdatest.com/wd/hub";      
public String platform;      
public String browserName;      
public String browserVersion;     
public RemoteWebDriver driver = null;      
boolean status = false;            
@Parameterized.Parameters      
public static LinkedList<String[]> getEnvironments() throws Exception {         
LinkedList<String[]> env = new LinkedList<String[]>();         
env.add(new String[]{"WIN10", "chrome", "70.0"});         
env.add(new String[]{"macos 10.12","firefox","62.0"});         
env.add(new String[]{"WIN8","internet explorer","11"});         
return env;     }    public JUnitConcurrentTodo(String platform, String browserName, String browserVersion) {         
this.platform = platform;         
this.browserName = browserName;         
this.browserVersion = browserVersion;      }    
@Before     
public void setUp() throws Exception {        
DesiredCapabilities capabilities = new DesiredCapabilities();         
capabilities.setCapability("browserName", browser);         
capabilities.setCapability("version", browserVersion);         
capabilities.setCapability("platform", platform); // If this cap isn't specified, it will just get the any available one         
capabilities.setCapability("build", "JUnitParallelSample");         
capabilities.setCapability("name", "JUnitParallelSampleTest");         
capabilities.setCapability("network", true); // To enable network logs         
capabilities.setCapability("visual", true); // To enable step by step screenshot         
capabilities.setCapability("video", true); // To enable video recording         
capabilities.setCapability("console", true); // To capture console logs         
try {            
driver = new RemoteWebDriver(new URL("https://" + username + ":" + accesskey + gridURL), capabilities);         
} catch (MalformedURLException e) {             
System.out.println("Invalid grid URL");         
} catch (Exception e) {             
System.out.println(e.getMessage());         
}     }        
@Test
public void testParallel() throws Exception {        
try {               //Change it to production page             
driver.get("https://4dvanceboy.github.io/lambdatest/lambdasampleapp.html"); //Let's mark done first two items in the list.               
driver.findElement(By.name("li1")).click();             
driver.findElement(By.name("li2")).click(); // Let's add an item in the list.               
driver.findElement(By.id("sampletodotext")).sendKeys("Yey, Let's add it to list");             
driver.findElement(By.id("addbutton")).click(); // Let's check that the item we added is added in the list.             
String enteredText = driver.findElementByXPath("/html/body/div/div/div/ul/li[6]/span").getText();             
if (enteredText.equals("Yey, Let's add it to list")) {                 
status = true;             }         } catch (Exception e) {             
System.out.println(e.getMessage());         }     }        
@After     public void tearDown() throws Exception {        
if (driver != null) {             
((JavascriptExecutor) driver).executeScript("lambda-status=" + status);             
driver.quit();         }     } }

  • Web Application Testing With JUnit and Selenium on the Cloud Is a Must

    Cloud testing means testing cloud-based applications that are hosted on a cloud. Using Selenium along with JUnit to test cloud services for web apps becomes the most obvious choice due to its capabilities to run the script on multiple browsers and platforms with any language support one choose for. The reason makes the incorporation between JUnit and Selenium a lucrative choice for performing cross-browser testing. With the use of JUnit, it provides a more structured way of writing your test that leads to better maintenance, quality, and effectiveness as compared to without using any frameworks like JUnit. LambdaTest, as a cross-browser testing tool, could help you significantly cut short on the time and effort you put in for executing automation testing with JUnit and Selenium. LambdaTest offers a Selenium grid consisting of more than 2000+ browsers and also supports multiple programming languages such as Javascript, Python, Ruby, C#, and PHP. Using Maven and Jenkins with Selenium and JUnit helps make a more powerful, smoother, and end-to-end automation experience for cloud-based application, thereby providing for robustness to the whole flow. We will be demonstrating that in our upcoming articles, so stay tuned and happy testing!

JUnit unit test mobile app Web application Web Service JAR (file format) operating system Compatibility (chemical) Annotation

Published at DZone with permission of Sadhvi Singh. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Top 7 Cross Browser Testing Tools in 2021
  • Difference Between Cross-Browser Testing and Responsive Testing
  • How to Quickly Build a Progressive Web App Using Lightning Web Components
  • 6 of the Best API Testing Tools in the Market

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!