Skip to content

Selenium Web Driver Java – User and passwords Always used

I have many codes that I wrote the user and the password but I wanted one way of to declare and call in all codes.

Is this exist?

public class Cadastro_Produto_ERP4ME {

@Test
public void iniciar_cadastro() throws InterruptedException {
    WebDriver driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("https://forme-hml.alterdata.com.br/");
    Thread.sleep(1000);
    driver.findElement(By.id("email-login")).sendKeys("user.dsn.shop"); **<<<<<<<<**
    driver.findElement(By.xpath("//form/div[2]/div/input")).sendKeys("senha"); **<<<<<<<<**

Answer

If I understand correctly you need to loop a set of credentials.

An example where usernames and passwords are stored as Map<String, String> object.

You can loop all entries in one driver instance or create new driver instance for every entry.

package selenium;

import java.util.HashMap;
import java.util.Map;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Cadastro_Produto_ERP4ME {

    public static Map<String, String> credentialsMap = credentialsMap(); 
    
    public static Map<String, String> credentialsMap() {
        Map<String, String> credentialsMap = new HashMap<String, String>();
        credentialsMap.put("username1", "password1");
        credentialsMap.put("username2", "password2");
        // etc.
        return credentialsMap;
    }
    
    public void iniciar_cadastro() throws InterruptedException {
        for (Map.Entry<String, String> entry: credentialsMap.entrySet()) {
            // new driver for each entry
            WebDriver driver = new ChromeDriver();
            driver.manage().window().maximize();
            driver.get("https://forme-hml.alterdata.com.br/");
            Thread.sleep(1000);
            driver.findElement(By.id("email-login")).sendKeys(entry.getKey());
            driver.findElement(By.xpath("//form/div[2]/div/input")).sendKeys(entry.getValue());
            // continue to login
        }
    }
    
    public void iniciar_cadastro2() throws InterruptedException {
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("https://forme-hml.alterdata.com.br/");
        for (Map.Entry<String, String> entry: credentialsMap.entrySet()) {
            // loop though map in one window
            Thread.sleep(1000);
            driver.findElement(By.id("email-login")).sendKeys(entry.getKey());
            driver.findElement(By.xpath("//form/div[2]/div/input")).sendKeys(entry.getValue());
            // reload login page or clear login form
        }
    }
    
}

The credentialsMap can be ofc used as argument.