I want to automate invalid and valid credentials - java

I am doing Selenium automation with page factory design pattern for a web application. Now I want to do automate valid valid, invalid invalid, valid invalid credential for a login page. How is it?
My complete code is
package com.docmgr.Pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.WebElement;
public class LoginPage
{
WebDriver driver;
public LoginPage(WebDriver driver)
{
this.driver=driver;
}
#FindBy(how=How.NAME,using="username")
#CacheLookup
WebElement username;
#FindBy(how=How.NAME,using="password")
#CacheLookup
WebElement password;
#FindBy(how=How.CLASS_NAME,using="button")
#CacheLookup
WebElement button;
#FindBy(how=How.LINK_TEXT,using="Forgot Password")
#CacheLookup
WebElement fp;
public void login_Doc(String uid,String pas)
{
username.sendKeys(uid);
password.sendKeys(pas);
button.click();
}
}
package com.docmgr.TestCases;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.Test;
import com.docmgr.Pages.LoginPage;
import Helper.BrowserFactory;
public class LoginTest
{
#Test
public void chechValidUser()
{
System.setProperty("firefox.webdriver.marionette","pathToGeckodriver");
WebDriver driver=BrowserFactory.startBrowser("firefox","54.68.159.876/docmgr");
LoginPage login=PageFactory.initElements(driver,LoginPage.class);
login.login_Doc("jgsdg","123");
}
}
package Helper;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class BrowserFactory
{
static WebDriver driver;
public static WebDriver startBrowser(String browsName,String url)
{
if(browsName.equals("firefox"))
{
driver=new FirefoxDriver();
}
driver.manage().window().maximize();
driver.get(url);
return driver;
}
}

Pass an extra parameter for login_Doc method which denotes that the give user name and password is valid or not. Look at below example.
public void login_Doc(String uid,String pas,boolean isValidCredential)
{
username.sendKeys(uid);
password.sendKeys(pas);
button.click();
if(isValidCredential == true){
// check if user is logged in successfully and click on logout button
} else {
//check appropriate error message is displayed
}
}
and call the login.login_Doc method as,
login.login_Doc("admin","admin",true); //valid credential
login.login_Doc("admin","admin123",false); //invalid credential

Your tests will look like this:
public class LoginTest
{
#Test
public void chechValidUser()
{
login.login_Doc("valid","valid");
}
#Test
public void chechValidInvalidUser()
{
login.login_Doc("valid","invalid");
String bodyText = driver.findElement(By.tagName("body")).getText();
Assert.assertTrue("Text not found!", bodyText.contains("Invalid Password"));
}
#Test
public void chechInvalidInvalidUser()
{
login.login_Doc("invalid","invalid");
String bodyText = driver.findElement(By.tagName("body")).getText();
Assert.assertTrue("Text not found!", bodyText.contains("Invalid Username"));
}
}
If you change your login function to this:
public void login_Doc(String uid,String pas)
{
System.setProperty("firefox.webdriver.marionette","pathToGeckodriver");
WebDriver driver=BrowserFactory.startBrowser("firefox","54.68.159.876/docmgr");
LoginPage login=PageFactory.initElements(driver,LoginPage.class);
username.sendKeys(uid);
password.sendKeys(pas);
button.click();
}

Related

Automation login test is failed, but login in web page is successful

I am trying to write automation tests for login page. The problem is that my code works as expected (web page is opened and I am logged in) but test is failed. When I trying to debug my code it says that I have problem with clickLoginButton() function but I have no idea what is wrong. Could you please help me? Thanks in advance!
Here is my class with elements and methods:
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;
public class LoginData {
private WebDriver driver;
#FindBy(how = How.XPATH, using = "//a[#class = 'close-modal-window']/img")
private WebElement close;
#FindBy(how = How.XPATH, using = "//input[#id='email']")
private WebElement emailField;
#FindBy(how = How.XPATH, using = "//input[#id = 'password']")
private WebElement passwordField;
#FindBy(how = How.XPATH, using = "//app-submit-button/button[#class = "//button[#class = 'primary-global-button']")
private WebElement loginButton;
#FindBy(how = How.XPATH, using = "//*[#id='header_user-wrp']/li[1]/a")
private WebElement userName;
public LoginData(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
//("click on 'close' button")
public LoginData clickCloseIcon() {
close.click();
return this;
}
//fill in Email
public LoginData inputEmail(String emailInput) {
emailField.click();
emailField.clear();
emailField.sendKeys(emailInput, Keys.ENTER);
return this;
}
//input password | value = {passwordInput}
public LoginData inputPassword(String passwordInput) {
passwordField.click();
passwordField.clear();
passwordField.sendKeys(passwordInput, Keys.ENTER);
return this;
}
// click on login button
public LoginData clickLoginButton () {
loginButton.click();
return new LoginData(driver);
}
//check if element is displayed when user is logged in
public boolean userNameIsDisplayed() {
return userName.isDisplayed();
}
}
And my login test:
import io.github.bonigarcia.wdm.WebDriverManager;
import org.junit.After;
import org.junit.Assert;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.time.Duration;
import static org.junit.Assert.*;
public class LoginDataTest {
private WebDriver driver;
final String BASE_URL = "https://ita-social-projects.github.io/GreenCityClient/#/";
#BeforeEach
public void beforeMethod() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.get(BASE_URL);
driver.findElement(By.partialLinkText("Увійти")).click();
}
#ParameterizedTest
#ArgumentsSource(EmailPasswordArgumentsProvider.class)
public void loginTest(String email, String password) {
try {
LoginData login = new LoginData(driver);
login.inputEmail(email).inputPassword(password).clickLoginButton();
Assertions.assertTrue(login.userNameIsDisplayed());
} catch (NullPointerException e) {
e.printStackTrace();
}
}
#AfterEach
public void AfterMethod() {
driver.quit();
}
}
Selenium should mimic human-like behavior. Meaning that you have to wait before clicking on elements, and wait before and after typing text in the web page.
// You have 2 ways to do this:
// 1. Just use sleep, for 0.3-1 seconds
Thread.Sleep(300);
// 2. use WebDriverWait:
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement we = wait.until(ExpectedConditions.
elementToBeClickable("By.Css or By.Xpath");
we.click();
Finding an element and immediately clicking or typing text into it is a bad practice.

Tests using Page Factory Design and Page Object Model opens two instances of the browser using Selenium and Java

I have a test in Selenium WebDriver with Page Object Model, if I run the following test open two windows in the Chrome browser, first window is empty in a URL line. How I can opening only one with onet.pl URL?
I trying deleting initialize Chrome driver but will have null.exception error.
What am I doing wrong?
package Pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.FindBy;
public class LoginPage {
private WebDriver driver;
//private WebDriverWait wait;
public LoginPage() {
this.driver = new ChromeDriver();
//wait = new WebDriverWait(driver,10);
}
#FindBy(xpath="//div[#class='col-md-12']//form")
private WebElement loginForm;
#FindBy(id="username")
private WebElement loginField;
#FindBy(id="password")
private WebElement passwordField;
#FindBy(xpath="//button[#class='btn btn-multisport-default btn-multisport-large btn-full-width login-button']")
private WebElement buttonLogin;
public void open() {
driver.get("https://onet.pl");
}
public void enterLogin() {
String login = "vadim1234#test.pl";
loginField.sendKeys(login);
}
public void enterPassword() {
String password = "Benefit!";
passwordField.sendKeys(password);
}
public void login() {
buttonLogin.click();
}
}
And test code:
import Pages.Dashboard;
import Pages.LoginPage;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.PageFactory;
import java.util.concurrent.TimeUnit;
public class LogIn {
#Test
public void correctLogin() {
System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver.exe");
WebDriver driver = new ChromeDriver();
LoginPage loginPage = PageFactory.initElements(driver, LoginPage.class);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
loginPage.open();
loginPage.enterLogin();
loginPage.enterPassword();
loginPage.login();
driver.close();
driver.quit();
Dashboard dashboard = new Dashboard(driver);
dashboard.getLoggedUser();
}
}
From your test class as you are passing the reference of the driver:
LoginPage loginPage = PageFactory.initElements(driver, LoginPage.class);
In LoginPage class, within the constructor, instead of:
public LoginPage() {
this.driver = new ChromeDriver();
//wait = new WebDriverWait(driver,10);
}
you need to do reuse the instance passed as follows:
public LoginPage(WebDriver loginPageDriver) {
this.driver=loginPageDriver;
}
That would solve the issue of 2 browsers getting opened.
References
You can find a couple of relevant detailed discussions in:
Selenium [Java] PageFactory Design : Where do I write my Assertions following Page Object Model

How to test a Login page which have other tests?

I am new to selenium web-driver. I am writing test to test a login page. My issue is- I have 2 tests, one for valid login and one for invalid login. Ideally, they should be independent but in my case they one case opens the page after login so another test fails.
I have tried relaunching the browser for every test but I don't think that's ideal.
Login Page
package com.ninja.pages;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
public class LoginPage
{
// http://tutorialsninja.com/demo/index.php?route=account/login
WebDriver driver;
#FindBy(how = How.XPATH, using = "//input[#id='input-email']")
WebElement email;
#FindBy(how = How.XPATH, using = "//input[#id='input-password']")
WebElement password;
#FindBy(how = How.XPATH, using = "//input[#class='btn btn-primary']")
WebElement login;
#FindBy(how = How.XPATH, using = "//div[#class='alert alert-danger alert-dismissible']")
WebElement warning;
public LoginPage(
WebDriver driver)
{
this.driver = driver;
}
public String getTitle()
{
return driver.getTitle();
}
public String doLoginValid(String email1, String pwd)
{
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
email.sendKeys(email1);
password.sendKeys(pwd);
login.click();
return driver.getTitle();
}
public String doLoginInValid(String email1, String pwd)
{
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
email.sendKeys(email1);
password.sendKeys(pwd);
login.click();
return warning.getText();
}
}
LoginPageTest
package com.ninja.testcases;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import com.ninja.pages.LoginPage;
import com.ninja.util.BrowserFactory;
public class LoginPageTest
{
static LoginPage loginPage;
static WebDriver driver;
#BeforeAll
public static void makeConnection()
{
driver = BrowserFactory.stratBrowser("chrome");
loginPage = PageFactory.initElements(driver, LoginPage.class);
}
#BeforeEach
public void startWebsite()
{
BrowserFactory.startWebsite("http://tutorialsninja.com/demo/index.php?route=account/login");
assertEquals("Account Login", loginPage.getTitle());
}
#Test
public void testDoLoginValid01()
{
assertEquals("My Account", loginPage.doLoginValid("ram#gmail.com", "Ram#123"));
}
#Test
public void testDoLoginInvalid02()
{
assertEquals("Warning: No match for E-Mail Address and/or Password.",
loginPage.doLoginInValid("ramq#gmail.com", "Ram#123"));
}
#Test
public void testDoLoginInvalid03()
{
assertEquals("Warning: No match for E-Mail Address and/or Password.",
loginPage.doLoginInValid("ram#gmail.com", "Rama#123"));
}
}
Sometimes closing the browser doesn't end the session. You should have an AfterEach that tries to find and click a LogOut button

NoSuchElementException in Selenium when testing login using Java

I am working on a Selenium testing framework tutorial of John Sonmez and ran into problem trying to perform the very first test. The test part consists of two methods: 1. LoginPage.GoTo(); which opens wordpress login page and 2. LoginPage.LoginAs("admin").Login(); which inserts username and clicks continue.
What happens when I run the test is wordpress loginpage opens and after 2 seconds blank Chrome browser opens and JUnit displays NoSuchElementException. The author of tutorial solved this problem adding some WebDriverWait and switchTo.ActiveElement.getAttribute() to LoginPage.GoTo(); method. However he is coding in C# and offers no solution for Java I'm coding in. I tried to apply WebDriverWait also but the problem is still there. Can anyone please suggest me how to solve this problem using WebDriverWait in Java.
LoginTest
import static org.junit.Assert.*;
import org.junit.Assert;
import org.junit.Test;
import wordpressAutomation.Driver;
import wordpressAutomation.LoginPage;
public class LoginTest extends Driver {
#Test
public void admin_user_can_login() {
LoginPage l = new LoginPage();
l.GoTo();
LoginPage.LoginAs("scenicrail").Login();
//Assert.assertTrue(DashboardPage.IsAt, "Failed to login");
}
}
LoginPage
import org.junit.Test;
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;
public class LoginPage extends Driver {
#Test
public void GoTo() {
openBrowser().get("https://wordpress.com/log-in");
}
public static LoginCommand LoginAs(String username) {
return new LoginCommand(username);
}
}
public class LoginCommand extends Driver {
private String username;
private String password;
public LoginCommand(String username) {
this.username = username;
}
public LoginCommand WithPassword(String password) {
this.password = password;
return this;
}
public void Login() {
WebElement login = openBrowser().findElement(By.xpath("//*[#id='usernameOrEmail']"));
login.sendKeys(username);
openBrowser().findElement(By.xpath("//button[#type = 'submit']")).click();
}
}
public class Driver {
public WebDriver openBrowser() {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\KatarinaOleg\\Desktop\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
//driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
return driver;
}
}
After opening the page, where you get the NoSuchElementException you can add in something like this.
FluentWait<WebDriver> webDriverWait = new WebDriverWait(driver, 25).pollingEvery(5, TimeUnit.SECONDS);
webDriverWait.until(ExpectedConditions.visibilityOf(webElement));
Just add in whatever element you want to use as your check to make sure the page has loaded
you have called the Openbrowser multiple times in Login Method from LoginCommand Class.So, It will be unnecessarily create different driver instance. So, your code needs to be modified as below along with explicit wait (Driver Class also needs to be changed as below)
Login Method from LoginCommand Class:
public void Login() {
WebDriverWait wait=new WebDriverWait(driver,20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#id='usernameOrEmail']")));
WebElement login = driver.findElement(By.xpath("//*[#id='usernameOrEmail']"));
login.sendKeys(username);
driver.findElement(By.xpath("//button[#type = 'submit']")).click();
}
Driver Class:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Driver {
WebDriver driver;
public WebDriver openBrowser() {
System.setProperty("webdriver.chrome.driver", "drivers/chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
//driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
return driver;
}
}
Edit: (dmin_user_can_login() method in LoginTest class)
#Test
public void admin_user_can_login() {
LoginPage l = new LoginPage();
l.GoTo();
l.LoginAs("scenicrail").Login();
//Assert.assertTrue(DashboardPage.IsAt, "Failed to login");
}
LoginPage Class:
import org.junit.Test;
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;
public class LoginPage extends Driver {
#Test
public void GoTo() {
openBrowser().get("https://wordpress.com/log-in");
}
public LoginCommand LoginAs(String username) {
return new LoginCommand(username);
}
}

Cannot get selenium webdriver Java script to run

Hi I'm new to webdriver I'm trying to get a script to run. When I run the script it opens the browser and enters the log in details but the #Test part does not. I've tried using css locator x path etc. but nothing I've tried works. Has anyone any ideas or advice that could help?
package firsttestngpackage;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class FirstTestNGFile {
public String baseUrl = "http://zzzz";
public WebDriver driver = new FirefoxDriver();
#BeforeTest
public void login() {
driver.get(baseUrl);
WebElement id = driver.findElement(By.id("z_username"));
id.sendKeys("todd");
WebElement pass = driver.findElement(By.id("z_password"));
pass.sendKeys("todd");
WebElement button = driver.findElement(By.name("login"));
button.submit();
}
#Test
public void createSub() {
driver.findElement(By.linkText("Customers")).click();
}
#AfterTest
public void terminateBrowser() {
driver.quit();
}
}
You were missing closing } and the selector for customers element may be the reason of failure as well
package firsttestngpackage;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class FirstTestNGFile {
public String baseUrl = "http://zzzz";
public WebDriver driver = new FirefoxDriver();
#BeforeTest
public void login() {
driver.get(baseUrl);
WebElement id = driver.findElement(By.id("z_username"));
id.sendKeys("todd");
WebElement pass = driver.findElement(By.id("z_password"));
pass.sendKeys("todd");
WebElement button = driver.findElement(By.name("login"));
button.submit();
}
#Test
public void createSub() {
driver.findElement(By.xpath("//*[.='Customers']")).click();
}
#AfterTest
public void terminateBrowser() {
driver.quit();
}
}

Categories

Resources