How to confirm the page title using selenium? - java

#Test(priority = 0)
public void test() throws Exception {
driver.get(baseUrl + "/");
driver.findElement(By.name("email")).clear();
driver.findElement(By.name("email")).sendKeys("lanka#ensiz.com");
driver.findElement(By.name("password")).clear();
driver.findElement(By.name("password")).sendKeys("123456");
driver.findElement(By.xpath("//button[contains(text(),'Sign In')]")).click();
}
#Test(priority = 1)
public void verifyHomepageTitle(){
String expectedTitle = "Placer Admin - Home";
String actualTitle = driver.getTitle();
Assert.assertEquals(actualTitle, expectedTitle);
}
#AfterClass(alwaysRun = true)
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
I'm new to automation testing.I want to make sure the valid user logins.For that i'm trying to verify the title of the page.But my test fail all the time,because it is execute before valid user going to the dashboard.how can I test this?Can i know the proper modifications for this code?
Please help..thanks

What you can do is, on the dashboard page select an element which is always there but is not on the login page. For example, a menu item or maybe a header.
Then create a wait like this at the end of the login test, so the test only completes after the dashboard is loaded:
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("XPath here")));
This will wait for a max of 5 seconds for the dashboard to load. The syntax could be wrong somewhere as I do everything in C#.

Use this code it is working fine in my machine :
public class User3806999 {
WebDriver driver;
WebDriverWait wait;
#BeforeClass
public void setUpClass(){
System.setProperty("webdriver.chrome.driver", "F:\\Automation\\chromedriver.exe");
driver = new ChromeDriver();
wait = new WebDriverWait(driver,30);
driver.manage().window().maximize();
driver.get("https://test.admin.placer.life/login");
}
#Test()
public void testLogin() throws Exception {
driver.findElement(By.name("email")).clear();
driver.findElement(By.name("email")).sendKeys("lanka#ensiz.com");
driver.findElement(By.name("password")).clear();
driver.findElement(By.name("password")).sendKeys("123456");
driver.findElement(By.xpath("//button[contains(text(),'Sign In')]")).click();
wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.id("user_menu"))));
//Assert something here
}
#Test(dependsOnMethods ={"testLogin"})
public void verifyHomepageTitle(){
String expectedTitle = "Placer Admin - Home";
String actualTitle = driver.getTitle();
Assert.assertEquals(actualTitle, expectedTitle);
}
#AfterClass(alwaysRun = true)
public void tearDown() throws Exception {
//logout here
}
}

Use the explicit wait as below before assertion:
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.titleContains(expectedTitle);

Related

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");

Prompting user input in selenium web driver before launching URL

I am trying to take user input then stored into the variable and i want to use that input into my program .
Here is my code , code is asking for user input but not loading the URL . It is just initiating the driver. Please someone correct me .
Current behavior:
Initiating the driver (IE shows the message " This is the Initial start page for wendriver server"
Asking for prompt .I gave my input in the prompt and click OK.
thats it .. after that code is not getting executed. Please help me
enter image description here
public class app{
public static void main(String[] args) throws Throwable
{
System.setProperty("webdriver.ie.driver", "C:\\Automation\\IEDriverServer.exe");
WebDriver driver = new InternetExplorerDriver();
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.promptResponse=prompt('Please enter the USER ID')");
if(isAlertPresent(driver)) {
// switch to alert
Alert alert = driver.switchTo().alert();
// sleep to allow user to input text
Thread.sleep(10000);
// this doesn't seem to work
alert.accept();
String ID = (String) js.executeScript("return window.promptResponse");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("my application URL");
driver.findElement(By.name("USERID")).sendKeys("username");
driver.findElement(By.name("user_pwd")).sendKeys("mypwd");
driver.findElement(By.name("submit")).submit();
.......
......
// some more code which is doing my application fucntionality
.......
......
........
private static boolean isAlertPresent(WebDriver driver) {
try
{
driver.switchTo().alert();
return true;
} // try
catch (NoAlertPresentException Ex)
{
return false;
}
}
}
If you need to take input (ie. URL) from promp then you may use JOptionPane's showInputDialog() method from Java Swing.
Code snippet:
String URL =JOptionPane.showInputDialog(null,"Enter URL");
Try following code; it should serve your purpose:
public class app{
public static void main(String[] args) throws Throwable
{
System.setProperty("webdriver.ie.driver", "C:\\Automation\\IEDriverServer.exe");
WebDriver driver = new InternetExplorerDriver();
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.promptResponse=prompt('Please enter the USER ID')");
isAlertPresent(driver);
String ID = (String) js.executeScript("return window.promptResponse");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("my application URL");
driver.findElement(By.name("USERID")).sendKeys("username");
driver.findElement(By.name("user_pwd")).sendKeys("mypwd");
driver.findElement(By.name("submit")).submit();
}
private static void isAlertPresent(WebDriver driver) {
try
{
driver.switchTo().alert();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // even though not needed
isAlertPresent(driver);
} // try
catch (NoAlertPresentException Ex)
{
}
}
}

Selenium Webdriver TestNG tests are "overwriting" each other

I am trying to run Selenium Webdriver tests in parallel on a single machine, using TestNG. I have 3 #Test methods, where 3 different users log in to the same application and reach the home page. I need #Test methods to run in parallel, and write to an ExtentReports report.
My problem is, despite 3 completely different methods in different classes, one of the users will be logged into 2 out of 3 of the browsers, leaving a user out.
The login method is located in a PageFactory page object class.
Here are my 3 test methods:
#Test(enabled = true, priority = 0)
public void JohnLogin() throws Exception {
ExtentTest t = ClientReportFactory.getTest();
try {
Login objLogin = new Login(getDriver());
String username = "John";
String password = "Password";
objLogin.SignIn(username, password);
HomePage objHomePage = new HomePage(getDriver());
assertTrue(objHomePage.clientName.getText().c‌​ontains("John"));
} catch (Exception e) {
}
}
#Test(enabled = true, priority = 1)
public void BobLogin() throws Exception {
ExtentTest t = ClientReportFactory.getTest();
try {
Login objLogin = new Login(getDriver());
String username = "Bob";
String password = "Password";
objLogin.SignIn(username, password);
HomePage objHomePage = new HomePage(getDriver());
assertTrue(objHomePage.clientName.getText().c‌​ontains("Bob"));
} catch (Exception e) {
}
}
#Test(enabled = true, priority = 2)
public void SamLogin() throws Exception {
ExtentTest t = ClientReportFactory.getTest();
try {
Login objLogin = new Login(getDriver());
String username = "Sam";
String password = "Password";
objLogin.SignIn(username, password);
HomePage objHomePage = new HomePage(getDriver());
assertTrue(objHomePage.clientName.getText().c‌​ontains("Sam"));
} catch (Exception e) {
}
}
So, if I pause the tests on the Homepage. I will have 2 browser windows opened as "John", one "Bob" and no "Sam"... Causing failures.
Here's the PageFactory Object's login method.
public void SignIn(String strUsername, String strPassword) throws InterruptedException {
WebDriverWait wait = new WebDriverWait(driver, 15);
username.clear();
username.sendKeys(strUsername);
password.clear();
password.sendKeys(strPassword);
submit.click();
wait.until(ExpectedConditions.visibilityOf(homePagePanel));
}
At first I was sure the problem was in the #BeforeMethod threading (As in, the tests were in a different thread than the #Before and #After). But I don't see how that could be the case. The Base Test method successfully opens and closes 3 browsers. It just seems like the #Test methods use each other's data! But just in case, here's my #Before and #After, with my Threading code.
public class BaseTest {
public String browser;
private ThreadLocal<WebDriver> threadedDriver = new ThreadLocal<WebDriver>();
#BeforeMethod(alwaysRun = true)
#Parameters({ "browser"})
public void setup(String browser)throws MalformedURLException,
InterruptedException {
WebDriver driver = null;
if (browser.equalsIgnoreCase("Internet Explorer")) {
System.setProperty("webdriver.ie.driver", "C:\\Selenium\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
} else if (browser.equalsIgnoreCase("Firefox")) {
System.setProperty("webdriver.gecko.driver", "C:\\Selenium\\geckodriver.exe");
driver = new FirefoxDriver();
} else if (browser.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\chromedriver.exe");
driver = new ChromeDriver();
} else if (browser.equalsIgnoreCase("MicrosoftEdge")) {
System.setProperty("webdriver.edge.driver", "C:\\Selenium\\MicrosoftWebDriver.exe");
driver = new EdgeDriver();
}
setWebDriver(driver);
this.browser = browser;
ClientReportFactory.getTest(ExtentTestName, ExtentTestDescription);
baseURL = "testApp.com";
driver.get(baseURL);
driver.manage().window().maximize();
}
public WebDriver getDriver(){
return threadedDriver.get();
}
public void setWebDriver(WebDriver driver) {
threadedDriver.set(driver);
}
#AfterMethod
public void afterMethod() {
ClientReportFactory.closeTest(ExtentTestName, ExtentTestDescription);
getDriver().quit();
threadedDriver.set(null);
}
#AfterSuite
public void afterSuite() {
ClientReportFactory.closeReport();
if (getDriver() != null) {
getDriver().quit();
} else {
System.out.println("Drivers already closed");
}
}
Assuming that all of your #Test methods are in different classes, I am guessing that the problem is perhaps due to the fact that your ThreadLocal variable is NOT STATIC but is an instance variable. This causes the behaviour to be per thread per instance rather than the desired behaviour viz., per thread across all instances. You can refer to this StackOverFlow thread for a better explanation on this.
You would resort to using an instance variant of ThreadLocal if and only if all your #Test methods belong to the same test class (Because now you are only trying to ensure that the class level data member WebDriver is shared in a thread safe manner across all the test methods that belong to the same test class)
So if each of your #Test methods reside in its own Test class, then please try changing:
private ThreadLocal<WebDriver> threadedDriver = new ThreadLocal<WebDriver>();
to
private static ThreadLocal<WebDriver> threadedDriver = new ThreadLocal<WebDriver>();
You could try this.
public class DriverFactory(){
private static ThreadLocal<WebDriver> driverThread;
public WebDriver driver;
#Parameters("browser")
public WebDriver instantiateDriverObject(String browser) {
DriverFactory factory = new DriverFactory();
driver = factory.createInstance(browser); //Driver instantiation goes here
driverThread = new ThreadLocal<WebDriver>() {
#Override
protected WebDriver initialValue() {
webDriverPool.add(driver);
return driver;
}
};
return driver;
}
public WebDriver getDriver() {
return driverThread.get();
}
}

Unable to find a WebElement when invoking an ant job in Jenkins

I was trying to invoke an ant job in Jenkins, it failed since some web elements were not found (I find these elements by their ID). However, I can build the ant successfully in Eclipse without this issue. I was using Jenkins-1.651.3 in Window7.
public class SendEmail
WebDriver browser = new FirefoxDriver();
#Parameters("url")
#Test
public void openHomePage(String url) throws Exception
{
browser.get("https://exmail.qq.com/");
}
#Test(dependsOnMethods = "openHomePage" )
public void openLoginPage() throws Exception
{
WebElement loginButton = browser.findElement(By.linkText("登录"));
loginButton.click();
}
#Parameters({"username","password"})
#Test(dependsOnMethods = "openLoginPage" )
public void authentication(String username, String password) throws Exception
{
WebElement userNameField = browser.findElement(By.id("inputuin"));
WebElement passwordField = browser.findElement(By.id("pp"));
WebElement checkbox = browser.findElement(By.id("ss"));
WebElement buttonLogin = browser.findElement(By.id("btlogin"));
checkbox.click();
userNameField.sendKeys(username);
passwordField.sendKeys(password);
buttonLogin.submit();
}
Add some implicit wait after creating driver instance:
WebDriver browser = new FirefoxDriver();
browser.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
And also add some explicit wait before before finding username input field like
WebDriverWait wait = new WebDriverWait(browser, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("inputuin"))));

Element is not clickable(x,y) even there is no scroll in page have tried thread.sleep()

I am unable to click on the "Login" button provided in the header I am new to selenium, here is the code snippet
public class Muft_Mashwara_login {
public WebDriver driver= null;
#BeforeMethod
public void startBrowser () {
driver= new FirefoxDriver();
driver.get("http://sqa.muftmashwara.be.vteamslabs.com/home");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
}
#Test
public void Click()throws InterruptedException {
//Thread.sleep(3000);
driver.findElement(By.xpath(".//*[#id='header2']/nav/div/ul/li/a")).click();
WebElement loginTxt = driver.findElement(By.xpath("html/body/main/div/section/article[2]/div/div/form[1]/div[1]/div/input"));
loginTxt.sendKeys("test#test.com");
}
#AfterMethod
public void Close() {
driver.close();
}
}
It only works if I uncomment "Thread.sleep". I don't know how to implement dynamic wait in this case.
Should work with something like this:
WebDriverWait webDriverWait = new WebDriverWait(driver, 5); // Wait up to five seconds.
wait.until(ExpectedConditions.visibilityOfElementLocated(
By.xpath(".//*[#id='header2']/nav/div/ul/li/a"))).click();
// Or perhaps:
//webDriverWait.until(ExpectedConditions.elementToBeClickable(
// By.xpath("//xpath"))).click();
You may also want to add this one before clicking, as the loading overlay interferes with clicking for some versions of webdriver.
wait.until(ExpectedConditions.invisibilityOfElementLocated(
By.xpath("//div[#id='cover']")));
I think the webdriverwait is not working correctly for this scenario so Thread.sleep will do.
Try this code, it ran sucessfully at my end.
And always Use Css before you think of XPath.
Css are faster than Xpath.
#Test
public void test() throws InterruptedException, AWTException{
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://sqa.muftmashwara.be.vteamslabs.com/home");
Thread.sleep(10000L);
driver.findElement(By.cssSelector(".fa.fa-lock")).click();
}
use the below code:
public class Muft_Mashwara_login {
public WebDriver driver= null;
#BeforeMethod
public void startBrowser () {
driver= new FirefoxDriver();
driver.get("http://sqa.muftmashwara.be.vteamslabs.com/home");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
}
#Test
public void Click()throws InterruptedException {
//use javascript click here
WebElement elem = driver.findElement(By.cssSelector("li>a[href='/login']"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", elem);
WebElement loginTxt = driver.findElement(By.cssSelector("div.form-group.ng-invalid>input[name='username']"));
loginTxt.click();
loginTxt.sendKeys("test#test.com");
}
#AfterMethod
public void Close() {
driver.close();
}
}
but if u want to learn how to use dynamic wait,see the below example:
WebDriverWait webDriverWait = new WebDriverWait(driver, 20);
webDriverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("ue selector")));
//u can use by xpath or class or name here also
// this will until the element is visible to the page

Categories

Resources