Eclipse - Can't see assert outcome in console - java

My Java is quite basic and I am very new to Selenium and I'm testing to see how it works. For some reason in my code, I can see the "assert" outcome in the console, whilst in another part I cannot. I've logged messages to the console before and after the assertation (both of which show) but the assertation result does not.
package automationFramework;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.junit.Assert.*;
public class Weather {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.gecko.driver", "//home//aaronh//Documents//Drivers//geckodriver");
// System.setProperty("webdriver.gecko.driver",
// "//home//aaron//JARs//geckodriver-v0.14.0-linux64//geckodriver");
WebDriver driver = new FirefoxDriver();
// launch browser and go to the website
String url = "https://www.bbc.com/weather";
driver.get(url);
driver.manage().window().maximize();
// search weather information for Bristol
WebElement location = driver.findElement(By.name("search"));
location.clear();
location.sendKeys("Bristol, Bristol");
// click search button
WebElement search = driver.findElement(By.name("submitBtn"));
search.click();
// this assertion fails because it checks the title before the search and IS LOGGED TO THE CONSOLE
// for
// Bristol weather has finished
// String bristol = driver.getTitle();
// assertEquals("BBC Weather - Bristol", bristol);
System.out.println("before wait");
WebDriverWait wait = new WebDriverWait(driver, 5);
if (wait.until(ExpectedConditions.titleContains("BBC Weather - Bristol"))) {
String bristol = driver.getTitle();
System.out.println("before assert " + bristol);
// this does not log to the console
assertEquals("BBC Weather - Bristol", bristol);
System.out.println("after assert");
}
driver.close();
System.out.println("Test script executed successfully.");
System.exit(0);
}
}
Can someone please tell me why the assertation outputs in one place and not the other? I appreciate the getTitle is pointless because the code won't get these unless the title is what we're asserting but hey, I'm just testing it out.
Thanks.

You have to distinguish between the Console and the JUnit view itself.
Example:
#Test
public void test() {
System.out.println("1");
Assert.assertEquals("A", "A");
System.out.println("2");
Assert.assertEquals("A", "B");
System.out.println("3");
}
results in:
A) console output
1
2
B) JUnit view output
org.junit.ComparisonFailure: expected:<[A]> but was:<[B]>
at org.junit.Assert.assertEquals(Assert.java:115)
...
Long story short: works as expected; and more importantly: asserts that pass do not create any observable output!

Related

Although the text is present in the pagesource() when I execute pageSource().contains.(text), it returns false

I am trying to find the subheading text: "You can join this team without approval if you have a farzanshaikh.com email address."
Although this text is present in the page source, it always returns false for .contains()
Code:
package JUnitTesting;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class TestOne {
WebDriver driver;
String BaseUrl;
String TeamDomain = "farzanshaikh.com";
#Before
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "C:\\Automation\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
BaseUrl = "http://farzanshaikh.flock.co/";
driver.get(BaseUrl);
driver.manage().window().maximize();
}
#Test
public void test() {
String element = driver.getPageSource();
System.out.println(element);
if(driver.getPageSource().contains("You can join this team without approval if you have a "+TeamDomain+" email address.")){
System.out.println("The Sub Heading on the Team URL page is Correct");
}
else{
System.err.println("The Sub Heading on the Team URL page is Wrong.");
}
}
#After
public void tearDown() throws Exception {
Thread.sleep(2000);
driver.quit();
}
}
Well, I don't see any issue either in your code or in the result.
Manually when we look into the webpage we can see the text You can join this team without approval if you have a farzanshaikh.com email address.
But when we try to get the pagesource the part of the string cotaining the text reads like: You can join this team without approval if you have a <span class='domains-list'>{{canJoinDomains}}</span> email address.
Finally, you are trying to use contains to validate if the first string is present in the second string. Hence it fails. If you can reduce the first string to something like You can join this team without approval, it would return True.
Let me know if this answers your question.

Linktext is not working

Below is my code, which I have written while practicing Selenium webdriver. In below code linkText is not fetching required value. Done all the things given in previous answers pertaining to same issue.
package newpackage;
import org.openqa.selenium.*;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class PG9 {
public static void main(String[] args) {
System.setProperty("webdriver.ie.driver","D:\\Tools & Utilities\\IEDriverServer_x64_3.3.0\\IEDriverServer.exe");
InternetExplorerDriver driver = new InternetExplorerDriver();
String baseUrl = "http://www.monsterindia.com";
//WebDriverWait myWaitVar = new WebDriverWait(driver, 50);
driver.get(baseUrl);
//myWaitVar.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.linkText("Upload Resume")));
driver.findElement(By.linkText("Upload Resume")).click();
String expectedTitle = "Job Search | Job Vacancies | Job Opportunities in India | Monster India";
String actualTitle = "";
actualTitle = driver.getTitle();
/*
* compare the actual title of the page with the expected one and print
* the result as "Passed" or "Failed"
*/
if (actualTitle.contentEquals(expectedTitle)){
driver.findElement(By.id("name")).sendKeys("Abhay Dadhkar");
driver.findElement(By.id("mob_no")).sendKeys("9011134418");
driver.findElement(By.id("wordresume")).sendKeys("D:\\Abhay\\Abhay_Training_Profile\\Training_Profile\\AbhayDadhkar_Detail_Profile_Jan2017.docx");
} else
{
System.out.println("Test Failed");
}
driver.close();
// enter the file path onto the file-selection input field
WebElement uploadElement = driver.findElement(By.name("File name"));
uploadElement.sendKeys("D:\\Automation tools\\Selenium\\Selenium_Practice\\newhtml.html");
// check the "I accept the terms of service" check box
//driver.findElement(By.name("Open")).click();
// click the "UploadFile" button
driver.findElement(By.name("Open")).click();
}
}
By.linkText works only on <a> tags. If you want to locate by text use xpath instead
driver.findElement(By.xpath("//span[contains(., 'Upload Resume')]")).click();
You can also click the parent <div>
driver.findElement(By.className("fileUpload")).click();

Unable to click on few items on website

The website I am trying to automate is betting website and I have a scenario to automate a horse betting.
I am using selenium 3.0 with Java
From the site I am able to travel to horse race but unable to select Tomorrow and select the race. I tried using xpath, class and other methods but unable to click on these button.
website is
https://www.williamhill.com.au/
1 step. go to the above url
2. Select horse racing from top left corner or navigate to url (https://www.williamhill.com.au/racing?event=horseracing)
3.Click on Tomorrow I am unable to do this
4. Select on particular race from the table (unable to this too)
package automationFramework;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class horseRacing {
public static void main(String[] args) throws Exception {
String exePath = "D:\\chromedriver.exe";
System.setProperty("webdriver.chrome.driver", exePath);
WebDriver driver = new ChromeDriver();
//Launch the Online Store Website
driver.get("https://www.williamhill.com.au/");
Thread.sleep(5);
driver.manage().window().maximize();
String Title = driver.getTitle();
System.out.println(Title);
driver.findElement(By.className("MenuItem_text_N8V")).click();
Thread.sleep(25);
// driver.findElement(By.className("RaceGrid_raceTile_imG RaceGrid_raceDisabled_Q0m")).click();
driver.findElement(By.xpath("//*[#id='app']/div/div[4]/div/div/div/div[2]/div[1]/div/div[2]/div[2]/div[2]")).click();
// 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(5);
// Close the driver
// driver.quit();
}
}
I tried to click "TOMORROW" and succeeded.
package test;
import org.openqa.selenium.By;
import org.junit.*;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class NavigateToAUrl {
#Test
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("https://www.williamhill.com.au/racing?event=horseracing");
driver.findElement(By.xpath(".//*[#id='app']/div/div[4]/div/div/div/div[2]/div[1]/div/div[2]/div[2]/div[2]")).click();
}
}
Dot(.) is missing in your code driver.findElement(By.xpath("//*[#id='app']/div/div[4]/div/div/div/div[2]/div[1]/div/div[2]/div[2]/div[2]")).click();
(Before //*[#id~)

WebDriver: Unable to Click on 'Radio Button'

I have created two sets of code contained in two seperate classes
Task Required: need to click on the 'Cash' button on the PH payment page.
Class one = simple class, simple code = code works and can click on the cash option.
Class two = setup contains page objects, framework uses different structure = code is unable to click on the cash option when reaching the payment page = 'org.openqa.selenium.StaleElementReferenceException: Element not found in the cache'
I have used the same locators within both classes but when uses the correct locator in '2' its unable to click on the 'radio' button; as listed above i get the listed error; i have tried to create bespoke methods; using loops etc and different locators but nothing works.
Working code and class:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
public class TestClass {
#Test
public void test() throws InterruptedException {
//System.setProperty("webdriver.chrome.driver", "C:\\Users\\GBruno\\Desktop\\masteringSelenium\\Framework\\src\\test\\resources\\chromedriver.exe");
// WebDriver driver = new ChromeDriver();
WebDriver driver = new FirefoxDriver();
driver.get("http://www.pizzahut.co.uk");
driver.manage().window().maximize();
//click pizza button
driver.findElement(By.cssSelector("div[id='page'] [href='/menu/pizza']")).click();
//select any pizza to start order
driver.findElement(By.cssSelector("div[class='col-xxs-8 col-xs-6 col-sm-8 col-md-7 col-lg-6'] *> button")).click();
//enter postcode and find hut
Thread.sleep(2000);
driver.findElement(By.cssSelector("#ajax-postcode-txt")).sendKeys("TS1 4AG");
driver.findElement(By.cssSelector(" #get-store-btn")).click();
//click start order button
Thread.sleep(3000);
driver.findElement(By.xpath(".//*[#id='store-collection-section']/div[2]/div[4]/div[4]/div/a")).click();
//add pizza
Thread.sleep(5000);
driver.findElement(By.xpath(".//*[#id='pizza-product-list']/div/div[1]/div/div[2]/div[2]/div[3]/div/form/button")).click();
//click mini basket
driver.findElement(By.xpath("html/body/nav/div/div/div[3]/div/div[1]/div[2]/span[3]")).click();
Thread.sleep(2000);
//click checkout
driver.findElement(By.xpath(".//*[#id='divBasket']/div[1]/div/div[2]/div[2]/a")).click();
Thread.sleep(2000);
//checkout guest & enter details
driver.findElement(By.xpath(".//*[#id='frmCheckout']/div[2]/div/div[1]/a")).click();
driver.findElement(By.xpath(".//*[#id='ddlTitleSelectBoxIt']")).click();
driver.findElement(By.linkText("Mr")).click();
driver.findElement(By.xpath(".//*[#id='FirstName']")).sendKeys("Tom");
driver.findElement(By.xpath(".//*[#id='LastName']")).sendKeys("Hanks");
driver.findElement(By.xpath(".//*[#id='EmailAddress']")).sendKeys("tom_hanks12344566#mail.com");
driver.findElement(By.xpath(".//*[#id='ConfirmEmailAddress']")).sendKeys("tom_hanks12344566#mail.com");
driver.findElement(By.xpath(".//*[#id='PhoneNumber']")).sendKeys("01234 5647890");
driver.findElement(By.xpath(".//*[#id='btnFindAddress']")).click();
Thread.sleep(3000);
driver.findElement(By.xpath(".//*[#id='ddlAddressesToChooseSelectBoxItArrowContainer']")).click();
driver.findElement(By.linkText("K F C 189-191 Linthorpe Road Middlesbrough TS14AG")).click();
driver.findElement(By.xpath(".//*[#id='btnContinue']")).click();
driver.findElement(By.xpath(".//*[#id='payment-methods']/div[1]/div/label/input")).click();
}
}
Code dosnt work:
public void selectPaymentTypeAndPayForOrder() throws Exception {
Thread.sleep(3000);
driver.findElement(By.xpath(".//*[#id='payment-methods']/div[1]/div/label/input")).click();
driver.findElement(By.cssSelector(" form[id='CheckoutForm'] input[data-paymentname='Cash']")).click();
The following code resolved the issue:
List<WebElement> iframes = driver.findElements(By.tagName("iframe"));
if(iframes.size() == 0) {
Assert.fail();
} else {
// Frames present
Assert.assertTrue(true);
}

Unable to find dropdown list element in selenium

i have written a basic test using selenium. The test is failing as the selenium unable to select the item from drop down list.
My select statement is not getting executed. Also i have include this select statement within iframe as this falls under it.
Can you please let me know what is the issue with my select statement.
Here is my code for southwest website:
package Default;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
//import org.openqa.selenium.firefox.FirefoxDriver;
public class FirstWDWithoutRecording {
#Test
public void SouthWestSignUp() throws InterruptedException
{
//Open the FF/Chrome browser
//FirefoxDriver oBrw = new FirefoxDriver();
ChromeDriver oBrw = new ChromeDriver();
//Maximize Browser
oBrw.manage().window().maximize();
//Open/Launch www.southwest.com
System.setProperty("webdriver.chrome.driver", "E://chromedriver.exe");
oBrw.get("http://www.southwest.com/");
//Click on Sign up and Save
//Recognising
oBrw.findElement(By.linkText("Sign up")).click();
//oBrw.get("http://www.southwest.com/html/email/click_n_save_signup.html?clk=GFOOTER-CNS-ENROLL");
Thread.sleep(5000);
//Enter First Name
oBrw.switchTo().frame(0); //'0' as it is the only iframe on the page, the value is the index of all iframes on the page
//do your login actions
oBrw.findElement(By.xpath("//input[#id='FIRST_NAME']")).clear();
oBrw.findElement(By.xpath("//input[#id='FIRST_NAME']")).sendKeys("abc");
//Enter Last Name
oBrw.findElement(By.id("LAST_NAME")).clear();
oBrw.findElement(By.id("LAST_NAME")).sendKeys("Kish123");
//Enter Email ID
oBrw.findElement(By.id("EMAIL")).clear();
oBrw.findElement(By.id("EMAIL")).sendKeys("abc#Kish123.com");
//Selecting Home Airport
Select uiHomeAp = new Select(oBrw.findElement(By.id("HOME_AIRPORT")));
uiHomeAp.deselectByVisibleText("Atlanta, GA - ATL");
//Accepting Conditions
oBrw.findElement(By.id("IAN")).click();
//Click Submit
oBrw.findElement(By.id("submit")).click();
//after return
oBrw.switchTo().defaultContent();
}
}
As #SiKing had stated, your issue is with your deselectByVisibleText(). You want selectByVisibleText().
uiHomeAp.selectByVisibleText("Atlanta, GA - ATL");
Also wanted to point out that it might be easier if you are just getting started, to check out the getting started with selenium framework. If you're using maven, you could do:
<dependency>
<groupId>io.ddavison</groupId>
<artifactId>getting-started-with-selenium-framework</artifactId>
<version>1.2</version>
</dependency>
then your test would look like this:
#Config(browser = Browser.CHROME, url="http://www.southwest.com/")
public class FirstWDWithoutRecording extends AutomationTest {
public void southWestSignUp() {
click(By.linkText("Sign up"))
.switchToFrame(0)
.setText("input#FIRST_NAME", "abc")
.setText("input#LAST_NAME", "Kish123")
.setText("input#EMAIL", "abc#Kish123.com")
.selectOptionByText("select#HOME_AIRPORT", "Atlanta, GA - ATL")
.check("#IAN") // check the terms and conditions
.click("#submit") // form submitted
.switchToDefaultContent()
;
}
}

Categories