As an automation tester, it is common to encounter Selenium test automation scenarios where the same test cases need to be executed over and over again, just with different inputs and environment configurations, making the work tedious and redundant.

To deal with this use case redundancy, most people choose to parameterize tests. With parameterized testing, testers can run the same automated test scripts again, but with different data. Parameterized testing helps save time by using test methods to gather results.

In this article, I’ll show you how to implement JUnit parameterized testing for Selenium test automation. If you are not familiar with JUnit, see the article on automated testing using JUnit and Selenium.

  • JUnit 5 and Selenium Basics
  • JUnit 5 and Selenium Basics (ii)
  • JUnit 5 and Selenium Basics (3)

Why do YOU need JUnit parameterized tests?

Let’s start with a Selenium JUnit test scenario where there is a requirement to perform Selenium automated tests on a shopping site. Testers have already scripted test cases for the product, but you quickly realize that you need to run them repeatedly not only for different products, but also for different OS and browser versions to ensure compatibility.

First, for Selenium test automation, we need multiple data sets to execute tests. What follows is a cross-browser matrix that covers the reality of the vast majority of users. Second, we need to learn how to write test scripts to retrieve data from a stored dataset.

It is important to note that when automated testing of Web applications, it is difficult to maintain a single stable and reliable data source for subsequent iterations of testing. More often than not, it is difficult to create multiple Selenium test automation scripts for the same test case in the same configuration, except for special base data and some business scenarios that rarely change. In short, hard coding just leads to a lot of maintenance work, so you need JUnit parameterized tests to help you save time and effort in the Selenium test automation cycle.

In order to use multiple data sets in our Selenium test automation scripts, the first thing that came to mind was to use an Excel worksheet to retrieve that data. However, when you want to create more specific Selenium test automation scripts, you need to use a multi-in-one framework like JUnit. JUnit enables us to write test cases in a more robust manner and gives us multiple capabilities, one of which is parameterization.

JUnit Parameterized type

Two effective ways to parameterize tests using JUnit.

  • use@ParametersAnnotations are parameterized
  • useExcelThe file is parameterized

First, you parameterize with the @Parameters annotation, which allows test data to be passed to Selenium scripts as a Java collection. Any data changes, all the tester needs to do is edit the collection with the required data.

Second, with Excel parameterization, testers are free to take data from external files, no matter how much, and load it into Selenium test automation scripts.

We can also use JUnit Params dependencies to parameterize our tests by using the @parameterizedTest annotation instead of the @test annotation. You can also pass parameters to JUnit Parameterized Tests using various annotations listed below:

  • @ValueSource
  • @EnumSource
  • @CsvSource
  • @CsvFileSource
  • @MethodSource

Parameterization is done using the @parameters annotation

Here is a Demo for searching some keywords. Now, let’s see what the code would look like if we wrote raw code without the notion of parameterization.

package FunTester;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class TestNormExec {  	
  	WebDriver driver;
   	@Before
  	public void startUp(a){    	
         	System.out.println("---- Start testing ----");
  	System.setProperty("webdriver.chrome.driver"."Chromedriver. Exe path");
         	driver = new ChromeDriver();
  	driver.get("https://www.****.com/");
         	driver.manage().window().maximize();
  	}
  	
  	@Test
  	public void searchKeys(a){
         	String keyWrd = "FunTester";
         	WebElement srchBox = driver.findElement(By.name("q"));
         	srchBox.sendKeys(keyWrd + "\n");
         	String title = driver.getTitle();
         	System.out.println("The title is : " +title);
  	}
  	
   	@After
  	public void tearDown(a){
         	System.out.println("- end -"); driver.quit(); }}Copy the code

In order to run Selenium test automation with a different data set, the keyWrd object must manually change the value of the string each time a test case is run. To simplify the process of changing input values, test cases can be parameterized using JUnit parameterized tests. This will also help us eliminate redundancy in the Selenium test cases.

Now, let’s take a closer look at JUnit test parameterization for Selenium test automation. I will create a class that contains test methods. Notice that here I pass the keyword as a method parameter, unlike the previous method, where I stored the search keyword in a variable.

package FunTester;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
 
public class Search {
  
  	WebDriver driver;  	
  	@Test
  	public void searchKeys(String kyWrd, String kyWrd1){
         	System.out.println("---- Start testing ----");
  	System.setProperty("webdriver.chrome.driver"."Chromedriver. Exe path");
         	driver = new ChromeDriver();
  	driver.get("https://www.****.com/");
         	driver.manage().window().maximize();
         	WebElement srchBox = driver.findElement(By.name("q"));
         	srchBox.sendKeys(kyWrd + "" + kyWrd1 + "\n");
         	String title = driver.getTitle();
         	System.out.println("The title is : " +title);
         	System.out.println("- end -"); driver.quit(); }}Copy the code

In the next step, I’ll create a class with an @runwith annotation. This class will run tests on the new instance. In addition, I will create a constructor for this class that will store the data to be tested.

In this example, two variables are passed to the constructor. Next, to generate and return the test data, I’ll create a static method with a return type of Collection. Each entry in this collection will give data for a run, such as Selenium, FunTester, and so on, which will be executed once.

The Parameters annotation for this method provides the input data set for the test to run. This is the final code for this class.


package FunTester;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

@RunWith(Parameterized.class)
public class SearchTest {

  	private String kyWrd1;

  	private String kyWrd2;

  	private SearchGoogle searchGoogle;
   	public SearchGoogleTest(String kyWrd1, String kyWrd2){
         	super(a);this.kyWrd1 = kyWrd1;
         	this.kyWrd2 = kyWrd2;
   	}
 
  	@Before
  	public void init(a){
         	search = new Search();
         	}
         	
  	@Parameterized.Parameters
  	public static Collection data(a){
         	return Arrays.asList(new Object[][]{{"FunTester"."FunTester"}, {"JMeter"."Selenium"}, {"UiAutomator"."appium"}});
  	}	
  	
  	@Test
  	public void testSearch(a){ searchGoogle.searchKeys(kyWrd1,kyWrd2); }}Copy the code

The final step in creating a JUnit parameterized test is to create a test run class that will drive our test execution. This class will run the tests with the help of junitcore.runclasses, and our test class will be passed to it as a parameter.

package parameterizedRun;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class Runner {
   	public static void main(String[] args){
   	
         	Result res = JUnitCore.runClasses(SearchTest.class);
     
         	for(Failure fail:res.getFailures()){ System.out.println(fail.toString()); } System.out.println(res.wasSuccessful()); }}Copy the code

Use Excel for parameterization

Parameterization using Excel data-driven testing (often referred to as parameterization) is an effective way to handle test scripts that require different test data. Data from external files is read at run time and loaded into the test script rather than being hard-coded.

Some common scenarios can be tests with multiple users searching for different keywords. The main benefit of this approach is code reusability without maintaining Selenium test automation scripts, just updating the test data in the files. Let’s look at how to parameterize our test cases in JUnit using a data-driven framework.

In the Selenium JUnit tutorial, the main element we need to parameterize Excel is the Excel worksheet. I created an Excel worksheet of keywords to search for and placed it under the Data folder in my project location.

Once we have the data ready, the next step is to create the utility class file that will load the Excel workbook and then read the data from the worksheet and the corresponding cells. Early on, I wrote some practices: Java uses POI to write excel documents as a solution, Java uses POI to read Excel documents as a solution.

Now that we have a class that contains a method to read data from Excel, let’s go ahead and write test methods in another class that pass parameters corresponding to the keywords we need to retrieve, while calling methods to fetch data from Excel files.

package FunTester;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class TestSearch {

	WebDriver driver;

	ReadExcel excel = new ReadExcel();	  	
  	@Before
  	public void startUp(a){
         	System.out.println("---- Start testing ----");
  	System.setProperty("webdriver.chrome.driver"."Chromedriver. Exe path");
         	driver = new ChromeDriver();
  	driver.get("https://www.****.com/");
         		driver.manage().window().maximize();
  	}
  	
  	@Test
  	public void searchKeys(a){
         	System.out.println("---- search keywords ----");
         	WebElement srchBox = driver.findElement(By.name("q"));   
         	srchBox.sendKeys(excel.getData(0.1.0) + "\n");                  	        	String title = driver.getTitle();
         	System.out.println("The title is : " +title);
  	}
  	
  	@After
  	public void tearDown(a){
         	System.out.println("---- End test ----"); driver.quit(); }}Copy the code

After running the code above, the Selenium test automation script will fetch Excel data from the second line of the Excel worksheet. To iterate over the test, refer to the scheme provided by the @Parameters annotation.


The public number FunTester first, original sharing enthusiasts, Tencent cloud, open source China and nuggets community recommended home page, Zhihu is the eighth level strong, welcome to pay attention to, exchange, prohibit unauthorized reprinting by third parties.

FunTester hot text selection

  • Programming thinking for everyone
  • 2020 Tester self-improvement
  • Fiddler Everywhere is the future
  • Test development engineer work skills
  • Selenium4 IDE, it’s finally here
  • Automated test soul three questions: What, why, and what to do
  • Why is test coverage so important
  • Let me tell you something. I don’t want to be tested
  • Automated testing framework
  • End-to-end testing in Agile