Data Driven Testing using JSON File In Selenium WebDriver
Data Driven Testing is nothing but fetching test data from an external data source and use it in the test script. External data source can be an excel file or a properties file or a text file or a database or a JSON file. In this article, we are going to learn how to fetch test data from a JSON file and use it in the test program.
Dependency Required :
<!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
Add the above dependency to the pom.xml file of your Maven Project.
JSON File:
{
"url": "http://newtours.demoaut.com",
"username": "mercury",
"password": "mercury",
"loginSuccessTitle": "Find a Flight: Mercury Tours:"
}
Test Script :
package jsonFileReader;
import java.io.FileReader;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
public class ReadJSONFile {
WebDriver driver;
@BeforeMethod
public void setUp() {
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("useAutomationExtension", false);
options.addArguments("--disable-notifications");
driver = new ChromeDriver(options);
}
@Test
public void verifyLoginFunctionality() {
try {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("./src/test/resources/loginCredential.json"));
JSONObject jsonObject = (JSONObject)obj;
String url = (String) jsonObject.get("url");
String username = (String) jsonObject.get("username");
String password = (String) jsonObject.get("password");
String expTitle = (String) jsonObject.get("loginSuccessTitle");
driver.get(url);
driver.findElement(By.name("userName")).sendKeys(username + Keys.TAB);
driver.findElement(By.name("password")).sendKeys(password + Keys.ENTER);
Thread.sleep(5000);
Assert.assertEquals(driver.getTitle(), expTitle);
}catch(Exception ex) {
System.out.println(ex.getMessage());
}
}
@AfterMethod
public void tearDown() {
if(driver !=null) {
driver.quit();
}
}
}
Comments
Post a Comment