LambdaTest Community

Find answers, support, and inspiration from other users

Questions
LambdaTest Community
Answered

How can I run parallel tests with Selenium WebDriver and Junit?

Can anyone please explain me how do i run parallel tests with selenium webdriver and junit.

Up Vote Down Vote 0 Votes
Posted 4 months ago

Answers


Cross browser testing as we know is a process where you test your website over multiple numbers of browser & browser versions running on different operating systems. This is done so 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 cross browser layout issues to cross browser compatible 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 could 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 every day time and effort.

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

Step 1. Downloading JUnit Jars

JUnit jar files can be downloaded from junit-team/junit4. 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, Javascript along with Java.

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 LambdaTest

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();
	}
	
	}

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 paramerterized class (org.junit.runners.Parameterized) and implements 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();
  }
  }
}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();
        }
    }
}
Up Vote Down Vote 0 Votes
Posted 3 months ago