I want to run my test case with Selenium script. But whenever I login with selenium it aways ask for verification code. I know I can do it using the Profile Id, but I want to do it with code. Something like we manually do once once we enter the password, and after that the platform doesn't ask for the verification code.
I tried below code:
public class MyClass {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.gecko.driver", System.getProperty("user.dir") +"\\geckodriver.exe");
DesiredCapabilities doc = DesiredCapabilities.firefox();
doc.setCapability("marionette", true);
WebDriver driver = new FirefoxDriver(doc);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(45, TimeUnit.SECONDS);
driver.get("https://login.salesforce.com/");
driver.findElement(By.id("username")).clear();
driver.findElement(By.id("username")).sendKeys("test@testing.com");
driver.findElement(By.id("password")).clear();
driver.findElement(By.id("password")).sendKeys("Qwerty@12345");
File file = new File("Cookies.data");
try
{
// Delete old file if exists
file.delete();
file.createNewFile();
FileWriter fileWrite = new FileWriter(file);
BufferedWriter Bwrite = new BufferedWriter(fileWrite);
// loop for getting the cookie information
// loop for getting the cookie information
for(Cookie ck : driver.manage().getCookies())
{
Bwrite.write((ck.getName()+";"+ck.getValue()+";"+ck.getDomain()+";"+ck.getPath()+";"+ck.getExpiry()+";"+ck.isSecure()));
Bwrite.newLine();
}
Bwrite.close();
fileWrite.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
...
Afer this I creted a new class and then set this cookie on it, like this:
...
try {
File file = new File("Cookies.data");
FileReader fileReader = new FileReader(file);
BufferedReader Buffreader = new BufferedReader(fileReader);
String strline;
while((strline=Buffreader.readLine())!=null){
StringTokenizer token = new StringTokenizer(strline,";");
while(token.hasMoreTokens()){
String name = token.nextToken();
String value = token.nextToken();
String domain = token.nextToken();
String path = token.nextToken();
Date expiry = null;
String val;
if(!(val=token.nextToken()).equals("null"))
{
expiry = new Date(val);
}
Boolean isSecure = new Boolean(token.nextToken()).
booleanValue();
Cookie ck = new Cookie(name,value,domain,path,expiry,isSecure);
System.out.println(ck);
driver.manage().addCookie(ck); // This will add the stored cookie to your current session
}
}
}catch(Exception ex){
ex.printStackTrace();
}
driver.get("https://login.salesforce.com/");
...
I am not sure wether this is correct or not because I am trying this for the 1st time. I took the reference from this link:
https://www.guru99.com/handling-cookies-selenium-webdriver.html
Please help me to find the issue.