JSON test data in Selenium Java - Build an Automation Script
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; import java.time.Duration; import static org.junit.jupiter.api.Assertions.assertTrue; public class LoginTest { public static void main(String[] args) throws Exception { // Setup WebDriver System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); try { // Open login page driver.get("http://example.com/login"); // Read JSON test data ObjectMapper mapper = new ObjectMapper(); JsonNode testData = mapper.readTree(new File("src/test/resources/loginData.json")); String username = testData.get("username").asText(); String password = testData.get("password").asText(); // Enter username WebElement usernameInput = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("username"))); usernameInput.sendKeys(username); // Enter password WebElement passwordInput = driver.findElement(By.id("password")); passwordInput.sendKeys(password); // Click login button WebElement loginButton = driver.findElement(By.id("loginBtn")); loginButton.click(); // Wait for dashboard URL wait.until(ExpectedConditions.urlContains("/dashboard")); // Assert URL contains /dashboard String currentUrl = driver.getCurrentUrl(); assertTrue(currentUrl.contains("/dashboard"), "User should be redirected to dashboard after login"); System.out.println("Test passed: User logged in successfully."); } finally { driver.quit(); } } }
This test script uses Selenium WebDriver with Java to automate the login test using JSON test data.
First, it sets up the ChromeDriver and opens the login page URL.
Then it reads the username and password from an external JSON file using Jackson's ObjectMapper.
It waits explicitly for the username input to be visible before entering the username and password.
After clicking the login button, it waits until the URL contains '/dashboard' to confirm successful login.
Finally, it asserts that the current URL contains '/dashboard' and prints a success message.
The driver quits in the finally block to ensure cleanup.
Now add data-driven testing with 3 different username and password combinations from JSON array
Practice
JSON test data in Selenium Java tests?Solution
Step 1: Understand JSON role in testing
JSON stores test data separately from the test code, so data changes don't require code changes.Step 2: Identify benefits of separation
This separation makes tests easier to maintain and reuse with different data sets.Final Answer:
It separates test data from test code for easier maintenance. -> Option AQuick Check:
JSON separates data and code = B [OK]
- Thinking JSON speeds up test execution
- Believing JSON fixes code bugs automatically
- Confusing JSON with code format
Solution
Step 1: Check correct constructor usage
The org.json library's JSONObject constructor accepts a Reader object to parse JSON text.Step 2: Match with options
JSONObject obj = new JSONObject(new FileReader("data.json")); uses new FileReader("data.json") which is a Reader, so it is correct.Final Answer:
JSONObject obj = new JSONObject(new FileReader("data.json")); -> Option AQuick Check:
JSONObject needs Reader input = A [OK]
- Passing filename string directly to JSONObject
- Using InputStream instead of Reader
- Passing filename string to BufferedReader constructor
data.json with content:{"username": "user1", "password": "pass123"}What will the following Java code print?
JSONObject obj = new JSONObject(new FileReader("data.json"));
System.out.println(obj.getString("username"));Solution
Step 1: Parse JSON content
The JSON has key "username" with value "user1".Step 2: Call getString("username")
This returns the string value for key "username", which is "user1".Final Answer:
user1 -> Option CQuick Check:
obj.getString("username") = "user1" [OK]
- Confusing username and password keys
- Expecting null if key exists
- Not handling JSONException properly
JSONObject obj = new JSONObject(new FileReader("testdata.json"));
String email = obj.getString("email");
System.out.println(email);Assuming the JSON file
testdata.json does NOT contain the key email.Solution
Step 1: Understand getString behavior
Calling getString on a missing key throws JSONException in org.json library.Step 2: Check code effect
Since "email" key is missing, the code throws JSONException at runtime.Final Answer:
It throws a JSONException at runtime. -> Option DQuick Check:
Missing key getString throws exception = D [OK]
- Expecting null or empty string instead of exception
- Ignoring exception handling
- Assuming code won't compile
{"users": [{"username": "user1", "password": "pass1"}, {"username": "user2", "password": "pass2"}]}Which approach correctly reads and uses this JSON data in Java to loop through each user?
Solution
Step 1: Identify JSON array access
The key "users" holds a JSON array, so getJSONArray("users") is correct.Step 2: Loop correctly over array
Loop from 0 to users.length() - 1, get each JSONObject, then extract username and password.Step 3: Check options
JSONArray users = obj.getJSONArray("users"); for (int i = 0; i < users.length(); i++) { JSONObject user = users.getJSONObject(i); String username = user.getString("username"); String password = user.getString("password"); // use username and password } correctly uses JSONArray, loops with i < length, and extracts data properly.Final Answer:
JSONArray users = obj.getJSONArray("users"); for (int i = 0; i < users.length(); i++) { JSONObject user = users.getJSONObject(i); String username = user.getString("username"); String password = user.getString("password"); // use username and password } -> Option BQuick Check:
JSONArray + for loop with i < length = A [OK]
- Using getJSONObject instead of getJSONArray for array
- Looping with i <= length causing IndexOutOfBounds
- Treating JSON array as string
Ready to prove it?
Pass the test and this pattern moves unknown
