How to use HashMap in Selenium WebDriver


In this article, I discussed how to create hash map in Java for data driven tests and read the data from the HasMap object. Please go through below example.




1) HashMap in Java

Example:

public class HashMapExample {

public static void main(String[] args) {

HashMap hm = new HashMap();

// Adding pairs to HashMap
hm.put(101, "John");
hm.put(102, "Scott");
hm.put(103, "David");

// Printing pairs from HashMap
System.out.println(hm);

// Remove a pair from HashMap by using key
hm.remove(102);

System.out.println(hm);

// Retrive a single pair from HashMap using key value
System.out.println(hm.get(103));

// Reading Keys and values from HashMap
for (Map.Entry m : hm.entrySet()) {

System.out.println((m.getKey() + "  " + m.getValue()));
}

}

}

Output:

{101=John, 102=Scott, 103=David}
{101=John, 103=David}
David
101  John
103  David



2) How to use HashMap in Selenium WebDriver Test case






Example:

import java.util.HashMap;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class LoginTestHM {

// method return HashMap object with data pairs
static HashMap logindata() {
HashMap hm = new HashMap();
hm.put("x", "mercury@mercury");
hm.put("y", "mercury1@mercury1");
hm.put("z", "mercury2@mercury2");

return hm;
}

public static void main(String[] args) throws Exception {

System.setProperty("webdriver.chrome.driver", "C://Drivers/chromedriver_win32/chromedriver.exe");
WebDriver driver = new ChromeDriver();

driver.get("http://newtours.demoaut.com/");

// Login as X
String credentials = logindata().get("x"); // Retriving value 'x' from
// HashMap

// Login as y
// String credentials = logindata().get("y");

// Login as z
// String credentials = logindata().get("x");

String uarr[] = credentials.split("@"); // separting value of 'x' int o
// 2 parts using delimeter '@'

driver.findElement(By.name("userName")).sendKeys(uarr[0]); // Passing
// value 1
// i.e
// username
// from
// array
driver.findElement(By.name("password")).sendKeys(uarr[1]); // Passing
// value 2
// i.e
// password
// from
// array
driver.findElement(By.name("login")).click();

// Validation
if (driver.getTitle().equals("Find a Flight: Mercury Tours:")) {
System.out.println("Test Passed");

} else {
System.out.println("Test failed");

}

driver.findElement(By.linkText("Home")).click();
}

}

Followers