Using DataProvider by initializing WebDriver one time within TestNG - java

I'm trying to check login page control by using dataprovider but i don't want to initialize webdriver again and again for each username password control. Once i come into login page, checking all concerned scenarios on login page in single time without starting another driver seems more convenient to me but i couldn't figure it out. When running following code, data[0][0] and data[0][1] is being correctly checked but it gives no such element on Login method having second priority test annotation when being tried to be typed data[1][0] and data[1][1]. Probably, it causes because driver is not looking at that page on that time. How can I handle this issue ?
error:
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//div[#class='q-input-wrapper email-input']//input[#class='q-input']"}
code:
public class TestCaseFirst {
public WebDriver driver;
#BeforeTest
public void Start() throws InterruptedException {
WebDriverManager.chromedriver().setup();
driver= new ChromeDriver();
driver.get("https://www.faxzas.com/");
driver.manage().window().maximize();
Thread.sleep(2000);}
#Test(priority=1)
public void RoadtoLogin() throws InterruptedException {
driver.findElement(By.xpath("//a[#title='Close']")).click();
Thread.sleep(1000);
driver.findElement(By.xpath("//div[#class='login-container']//span[#id='not-logged-in-container']")).click();;
Thread.sleep(1000);
}
#Test(dataProvider="loginInfos", priority=2)
public void Login(String mail, String password) throws InterruptedException {
driver.findElement(By.xpath("//div[#class='q-input-wrapper email-input']//input[#class='q-input']")).sendKeys(mail);
Thread.sleep(1000);
driver.findElement(By.xpath("//div[#class='q-input-wrapper']//input[#class='q-input']")).sendKeys(password);
Thread.sleep(1000);
driver.findElement(By.xpath("//button[#type='submit']")).click();
Thread.sleep(1000);
String description = driver.findElement(By.xpath("//div[#id='error-box-wrapper']//span[#class='message']")).getText();
System.out.println(description);
}
#DataProvider(name="loginInfos")
public Object[][] getData(){
Object[][] data = new Object[6][2];
data[0][0]="blackkfredo#gmail.com";
data[0][1]="";
data[1][0]="blackkfredo#gmail.com";
data[1][1]="443242";
data[2][0]="";
data[2][1]="1a2b3c4d";
data[3][0]="";
data[3][1]="";
data[4][0]="blackkfredogmail.com";
data[4][1]="1a2b3c4d";
data[5][0]="blackkfredo#gmail.com";
data[5][1]="1a2b3c4d";
return data;
}
}

You need to reset your page to the login page where you are expecting the element to be. Either put an #AfterMethod and go back to the page you are trying to test or put an #BeforeMethod for the same. You may even want to wrap up your find element calls and handle the exceptions by going back to the main page.

Related

Webdriver can't find element by locator set as variable in another class

I wrote automated tests with help of JUnit, Selenium Webdriver (v. 3.141.59) and Chromedriver (v. 2.45).
Firstly, I wrote a login test:
[...]
void loginTest() {
driver().findElement(By.id("login-button")).click();
driver().findElement(By.id("name")).sendKeys("mail#xx.com");
driver().findElement(By.id("password")).sendKeys("password");
driver().findElement(By.id("send")).click();
assertTrue(driver().findElement(By.id("logged-in-msg")).isDisplayed());
}
Everything worked fine, all good, test green.
Then I got some more and more complicated and long ids and xpaths I had to use, so I decided to keep tests short and nice and put all my locators in separate class, like this:
public class LocatorsList {
public static final String
SIGN_IN_BUTTON = "login-button",
LOG_IN_USERNAME = "name",
LOG_IN_PASSWORD = "password",
LOG_IN_BUTTON = "send",
SUCCESS_MSG = "logged-in-msg";
}
And my test:
[...]
void loginTest() {
driver().findElement(By.id(SIGN_IN_BUTTON)).click();
driver().findElement(By.id(LOG_IN_USERNAME)).sendKeys("mail#xx.com");
driver().findElement(By.id(LOG_IN_PASSWORD)).sendKeys("password");
driver().findElement(By.id(LOG_IN_BUTTON)).click();
assertTrue(driver().findElement(By.id(SUCCESS_MSG)).isDisplayed());
}
Then it stopped working. Webdriver sends errors:
org.openqa.selenium.NoSuchElementException: no such element:
Unable to locate element: {"method":"id","selector":"name"}
As I watched my test going, this element was right there on the page, webdriver even clicked at it as if it wanted to fill the field... but it didn't. Says 'unable to locate element'.
I tried to change chromedriver and selenium versions but it didn't help.
If that's honestly the only real change to the code, then could it be as simple as you missing the class name before the string? I.e:
driver().findElement(By.id(LocatorsList.SIGN_IN_BUTTON)).click()
This is most probably due to element not present, you need to wait for the element to be loaded. Use
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.presenceOfElementLocated((By.id(LOG_IN_USERNAME))));
After that you can perform the action on that particular element say sendKeys event.
public class Testing {
public static final String
SIGN_IN_BUTTON = "jsid-login-button",
LOG_IN_USERNAME = "login-email-name",
LOG_IN_PASSWORD = "login-email-password",
LOG_IN_BUTTON = "input[type='submit']";
WebDriver driver;
#BeforeMethod
public void setUp() {
System.setProperty("webdriver.chrome.driver", <driverLocation>);
driver = new ChromeDriver();
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
driver.get("https://9gag.com/");
}
#Test
public void demoTest() {
driver.findElement(By.id(SIGN_IN_BUTTON)).click();
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.presenceOfElementLocated((By.id(LOG_IN_USERNAME))));
driver.findElement(By.id(LOG_IN_USERNAME)).sendKeys(<YOUR_EMAIL>);
driver.findElement(By.id(LOG_IN_PASSWORD)).sendKeys(<YOUR_PASSWORD>);
driver.findElement(By.cssSelector(LOG_IN_BUTTON)).click();
}
#AfterMethod
public void tearDown() {
driver.quit();
}
}

How to quit the page if i type hello world on google search using selenium?

Hi guys I want to quit the page afte I type "Hello World" in google search using firefox browser and selenium
WebDriver driver = null;
public static void main(String args[]) {
SimpleSelenium ss = new SimpleSelenium();
ss.openBrowser();
ss.getPage();
ss.quitPage();
}
private void openBrowser() {
System.setProperty("webdriver.gecko.driver", "C:/geckodriver.exe");
driver = new FirefoxDriver();
}
private void quitPage() {
driver.quit();
}
private void getPage() {
driver.get("http://www.google.com");
}
1) Create a Junit test class
2) Initialize the driver in your setup method like
ChromeDriver driver = new ChromeDriver();//Download chromeDriver.exe file and point to location where you have installed the like as you mentioned. `driver.System.setProperty("webdriver.gecko.driver", "C:/geckodriver.exe");`
3) Create a test method with your business logic to type hello world
3) Create After and Before Class annotations for the methods .In After class annotation method you can write driver.quit.
You can refer to following link for more clarity
https://www.guru99.com/selenium-tutorial.html
I am Added sample format which is written Using java and testNG..Here Every time First before method will run then 1st test case will execute then after method will work then again before method work then next test case......In this way you can manage your test case and it will also generate Report also.Here you will get better explanation.
public class GoogleTest {
FirefoxDriver driver;
#BeforeMethod
public void setUp1() throws Exception {
System.setProperty("webdriver.gecko.driver", "D:\\\\ToolsQA\\trunk\\Library\\drivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void GoogleInputField() throws InterruptedException {
System.out.println("Hello world");
System.out.println("Hello world");
//Write Your test case for test case 1
}
#Test
public void google suggestion() throws InterruptedException {
//Write Your test case for test case 1
}
#AfterMethod
public void getResult(ITestResult result) throws IOException {
driver.quit();
}
}
Dont forget to add Firefox driver on gecko.driver path
I am assuming that you want to open the browser using selenium, load google and then listen till you MANUALLY enter "hello world" in the input box. The method listenForHelloWorld() will do that.
public static void main(String args[]) {
SimpleSelenium ss = new SimpleSelenium();
ss.openBrowser();
ss.getPage();
ss.listenForHelloWorld();
ss.quitPage();
}
private void listenForHelloWorld() {
// Get the search field
WebElement searchField = driver.findElement(By.name("q"));
int count = 1;
while (count++ < 20) {
// if search field value is "hellwo world" break loop which will eventallu lead to `quit()` as it is the next method to exit.
if (searchField.getAttribute("value").equalsIgnoreCase("hello world")) {
break;
}
Thread.sleep(5000)
}
}
If you are asking how to enter "hello world" in browser automatically use below.
driver.findElement(By.name("q")).sendKeys("hello world");

java Selenium driver.quit() is ignored

So I'm trying to learn how to use Selenium, and I found a tutorial on the internet on how to do it (http://toolsqa.com/selenium-webdriver/first-test-case/). I know I am using internet explorer rather than firefox, but I've followed the instructions on how to setup the IEDriver. The problem is that when I use their code to simply open and close a window, it opens it, and ignores the driver.quit() that is in there.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class FirstTestCase {
public static void main(String[] args) {
String service = "C:\\Users\\abc\\Documents\\IE Explorer Server\\IEDriverServer.exe";
System.setProperty("webdriver.ie.driver", service);
InternetExplorerDriver driver = new InternetExplorerDriver();
//Launch the Online Store Website
driver.get("http://www.store.demoqa.com");
// Print a Log In message to the screen
System.out.println("Successfully opened the website www.Store.Demoqa.com");
//Wait for 5 Sec
Thread.sleep(5000);
// Close the driver
driver.quit();
System.out.println(",");
}
}
It prints the comma I have set to print after it closes, but it doesn't actually close the browser. Thread.sleep() also gives an error. I've looked for over 3 hours for some kind of fix for this but couldn't find anything.
Try this:
public static void main(String[] args) throws InterruptedException {
String service = "C:\\Users\\abc\\Documents\\IE Explorer Server\\IEDriverServer.exe";
System.setProperty("webdriver.ie.driver", service);
InternetExplorerDriver driver = new InternetExplorerDriver();
//Launch the Online Store Website
driver.get("http://www.store.demoqa.com");
// Print a Log In message to the screen
System.out.println("Successfully opened the website www.Store.Demoqa.com");
//Wait for 5 Sec
Thread.sleep(5000);
// Close the driver
driver.quit();
System.out.println(",");
}
Here is the Answer to your Question:
I don't see any significant error in your code block. A few suggestions about the solution:
I retested your code block with Selenium 3.4.0, IEDriverServer 3.4.0 & MSIE 10.0 with only one additional parameter as
public static void main(String[] args) throws InterruptedException
and your code executes just fine. Whenever you add Thread.sleep(5000); in your code you may consider to add throws InterruptedException. But again, as per best practices we must avoid using Thread.sleep() and replace it by ImplicitlyWait or ExplicitWait.
You have used the InternetExplorerDriver implementation to initiate the driver. As per W3C standards you must consider using the WebDriver interface instead.
As per your comment driver.quit() not only closes the driver but also kills the driver instance and releases the memory.
Here is your own code with some small tweaks which works well at my side:
public static void main(String[] args) throws InterruptedException
{
String service = "C:\\your_directory\\IEDriverServer.exe";
System.setProperty("webdriver.ie.driver", service);
WebDriver driver = new InternetExplorerDriver();
//Launch the Online Store Website
driver.get("http://www.store.demoqa.com");
// Print a Log In message to the screen
System.out.println("Successfully opened the website www.Store.Demoqa.com");
// Quit the driver
driver.quit();
System.out.println(",");
}
Let me know if this Answers your Question

Possible to create a 'Master Step' within Cucumber (java)?

Possible to create a 'Master Step' within Cucumber (java)?
For example I have created many steps files which use repeated code, the repeated code initialises the browser etc within each of the step files.
Is it even possible to create a master step file which will which will house the driver setup etc and therefore execute the setup using 'Cucumber Before' before each of the steps.
My Code:
public class LoginStep {
WebDriver driver;
LoginPage loginPage;
#Before
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\deltaUser\\Desktop\\CucumberFramework\\PimCucumberFramework\\src\\test\\java\\resources\\other\\chromedriver.exe");
this.driver = new ChromeDriver();
this.driver.manage().window().maximize();
this.driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
loginPage = PageFactory.initElements(driver, LoginPage.class);
}
#Given("^User is on the PIM login page$")
public void user_is_on_the_PIM_login_page() throws Throwable {
loginPage.loginIntoAccount();
// loginPage.test();
}
#And("^enters the correct username$")
public void enters_the_correct_username() throws Throwable {
System.out.println("User neters the correct password inside the password textefield");
// loginPage.test2();
}
#And("^enters the correct password$")
public void enters_the_correct_password() throws Throwable {
System.out.println("Entered the correct password");
}
#When("^clicks on the login button$")
public void clicks_on_the_login_button() throws Throwable {
System.out.println("Clicked on the login button");
}
#Then("^user should be taken to the successful login page$")
public void user_should_be_taken_to_the_successful_login_page() throws Throwable {
System.out.println("Succesffully taken to the login page.");
}
}
I have tried the following code listed below, but the code dosnt work it seems to open the browser but then the other steps dont work (As if it has created a separate instance of the driver):
public class MasterStep {
WebDriver driver;
LoginPage loginPage;
#Before
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\gianni.bruno\\Desktop\\BuyAGiftCucumberFramework\\PimCucumberFramework\\src\\test\\java\\resources\\other\\chromedriver.exe");
this.driver = new ChromeDriver();
this.driver.manage().window().maximize();
this.driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
loginPage = PageFactory.initElements(driver, LoginPage.class);
}
}
Yes, it is possible. Use the concept of Inheritance.
Step 1: Create a Base Class
package com.base;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class TestBase2 {
public static WebDriver driver = null;
public void initialize() {
System.setProperty("webdriver.chrome.driver", "src/com/drivers/chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("https://www.google.co.in");
}
}
Step 2: Inherit this class using the extends keyword and call the initialize() method whenever you need.
Cucumber provides Before and After hooks you could use for this.
Hooks are blocks of code that can run at various points in the Cucumber execution cycle. They are typically used for setup and teardown of the environment before and after each scenario.
Before hooks run before the first step of each scenario.
Annotated method style:
#Before
public void doSomethingBefore() {
}
Lambda style:
Before(() -> {
});
After hooks run after the last step of each scenario, even when steps are failed, undefined, pending, or skipped.
Annotated method style:
#After
public void doSomethingAfter(Scenario scenario){
// Do something after after scenario
}
Lambda style:
After((Scenario scenario) -> {
});
The scenario parameter is optional, but if you use it, you can inspect the status of the scenario.

How to read the urls and html components used in the selenium test case

my selenium test code looks like below.
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://localhost:8080/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testSeleJunit() throws Exception {
driver.get(baseUrl + "/");
driver.findElement(By.linkText("New Item")).click();
driver.findElement(By.id("name")).clear();
driver.findElement(By.id("name")).sendKeys("i18n1");
driver.findElement(By.name("mode")).click();
driver.findElement(By.id("ok-button")).click();
}
From java code how can i get the url and the locators for which the test case is written?
If you are trying to get current url please use the following code
String url = driver.getCurrentUrl();
I am realy sure this is what you asked for ,if this is not what you asked for please explain your problem bit more

Categories

Resources