Selenium assertEqual - java

I have created a test case in Selenium WebDriver using the TestNG framework. I am trying to getText() and print it and also use it in Assert.assertEquals().
The problem I am facing is when I run this test case, it is showing error "java.lang.AssertionError: expected [] but found [Register here]" and also nothing prints in the "ab" variable.
My test case
#Test
public void signinpopup()
{
driver.get("http://uat.tfc.tv/");
driver.findElement(By.id("login_buttoni")).click();
String ab = driver.findElement(By.xpath("html/body/section[1]/div/div[1]/div[7]/div[2]/a")).getText(); // ab variable contains value "Register here"
System.out.println(ab);
System.out.println("hello1");
//Assert.assertEquals("Registe12r here", driver.findElement(By.xpath("html/body/section[1]/div/div[1]/div[7]/div[2]/a")).getText());
Assert.assertEquals(ab,"Regist5434er here");
}
One more thing: When I change the assert condition to Assert.assertEquals(ab,"Register here");, it will print the "ab" variable.
What is going on here?

Your error is pretty clear. The text you are looking for is Register here which is indeed found by Selenium.
The question is why did you write Regist5434er here in your assertEquals.
Just change that line to:
assertEquals(ab, "Register here");

You are getting an assertion failure, because 'ab' has an empty value. This might be because you are not locating the element properly. It is always recommended to use a relative XPath expression rather than an absolute XPath expression to locate the element.

Related

selenium web driver does not return the value from cssSelector in java

I have this jQuery selector as below.
jQuery("html body div input[name='customer_name']").val();
According to that I have created the selector for selenium as below.
By cusNameTxtField = By.cssSelector("html body div input[name='customer_name']");
First expression giving me the expected output in the browser console, but using the second expression it returns null value. Is there any issue with the second expression ?
And I am getting the String values as below in the java code.
String fieldText = waitForExpectedElement(cusNameTxtField, 10).getText();
Given this is an input element you might want to try
waitForExpectedElement(cusNameTxtField, 10).getAttribute("value");

(Java) How to verify external link redirection with Selenium?

Hi Guys!
Please take a look at my code, i'm trying to verify that my current webpage will be redirected to external site, in my case Google Play(open Google Play in the same tab). I guess i'm doing it wrong way cuz it pass with FireFox but failing with Chrome, here is my code...
String currentURL1 = driver.getCurrentUrl();
profilePage.clickOnGooglePlayLink();
String currentURL2 = driver.getCurrentUrl();
Thread.sleep(3000);
Assert.assertNotEquals(currentURL1, currentURL2, "Failed Redirected to Google Play");
log.info("Redirected to Google Play!");
I'm trying to assert it as NotEquals, is it any other solutin for this case?
Thanks for your time!
My code
It is pretty correct when the following line Fails :
Assert.assertNotEquals(currentURL1, currentURL2, "Failed Redirected to Google Play");
Analysis
If you look at the documentation of assertNotEquals, the signature is either of the following :
void org.testng.Assert.assertNotEquals(Object actual1, Object actual2)
void org.testng.Assert.assertNotEquals(Object actual1, Object actual2, String message)
Here both the assertNotEquals() method takes Object as an argument and performs evaluation.
But in your code, instead of an Object you have passed currentURL1 and currentURL2 and both of them are String as follows :
String currentURL1 = driver.getCurrentUrl();
//
String currentURL2 = driver.getCurrentUrl();
//
Assert.assertNotEquals(currentURL1, currentURL2, "Failed Redirected to Google Play");
So when both the Strings are casted to Objects, the comparison Fails as assertNotEquals() method doesn't takes String as an argument.
Solution
If you want to compare two Strings, a better option would be either of the following :
void org.testng.Assert.assertEquals(String actual, String expected)
void org.testng.Assert.assertEquals(String actual, String expected, String message)
Assert.assertEquals(actual, expected, message):- assertEquals assertion is useful to compare two string, boolean, byte[], char, double, float, int, etc.. and based on assertion result.
Assert.assertNotEquals(actual, expected, message) :-
assertion in selenium WebDriver is assertNotEquals assertion. It's function is opposite to assertEquals assertion. Means if both sides values will not match then this assertion will pass else it will fail. Here you can write your own message for failure condition.
Please refer this link

InvalidSelectorException while selecting value from the dropdown

I am trying to select value from the drodown. this is my code.
driver.findElement(By.xpath(".//*[#id='accountSelectContainer']/span/a/span[1]")).click();
driver.findElement(By.xpath("//ul[#id='ui-id-1']/li/a[equals(text(),'60091 - AFCENT')]")).click();
Now here i have hardcoded the value, which works perfect but i am reading my testdata from excel file . so instead of using direct hard code values , i want to declare my testdata in xpath and read it from excel file. so i tried to this:
Efforts
public void combobox(String testData)
{
driver.findElement(By.xpath(".//*[#id='accountSelectContainer']/span/a/span[1]")).click();
driver.findElement(By.xpath("//ul[#id='ui-id-1']/li/a[equals(text(),'"+testData+"')]")).click();
}
But i am getting the exception
org.openqa.selenium.InvalidSelectorException: invalid selector: Unable
to locate an element with the xpath expression
//ul[#id='ui-id-1']/li/a[equals(text(),'60091 - AFCENT')] because of
the following error: SyntaxError: Failed to execute 'evaluate' on
'Document': The string '//ul[#id='ui-id-1']/li/a[equals(text(),'60091
- AFCENT')]' is not a valid XPath expression.
I tried to change it to "+testData+" too instead of using '"+testData+"'
But same exception.
I tried this code too:
driver.findElement(By.xpath(".//*[#id='accountSelectContainer']/span/a/span[1]")).click();
List<WebElement> options = driver.findElements(By.xpath("//ul[#id='ui-id-1']/li"));
for (WebElement option : options) {
if(testData.equals(option.getText()))
option.click();
}
which works perfect but after this code execution , it is making my browser to wait for about 15 secs before executing next step or for quit too. i am not getting Why so ?
Please need suggestion or any ideas..
I doubt your fast attempt works perfect as xpath doesn't have equals. You would have gotten the same exception. To check for text equality use =
"//ul[#id='ui-id-1']/li/a[text()='"+testData+"']"
You can also use contains
"//ul[#id='ui-id-1']/li/a[contains(text(),'"+testData+"')]"
First: the exception you have got is because you xpath: //ul[#id='ui-id-1']/li/a[equals(text(),'60091 - AFCENT')] is not correct syntax.
Second: the code that you can run is not make your browser wait for 15s, it's just because problem about internet connection or you computer is a little slow.

Assertion issue in Java and Eclipse

I am using Java, Selenium Webdriver and Junit. Doing simple verification of title of Google , But it throws exception when Assertion fails I mean when title does not match.
Code :
public static void verifyTitle(String expectedTitle) {
//get the title of the page
String actualTitle = Base.getdriver().getTitle();
// verify title
assertThat(actualTitle, equalTo(expectedTitle));
}
I am calling in main method : verifyTitle("Hello");
Output :
> Exception in thread "main" java.lang.AssertionError: Expected:
> "Hello"
> but: was "Google" at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20) at
> org.junit.Assert.assertThat(Assert.java:956) at
> org.junit.Assert.assertThat(Assert.java:923) at
> Modules.Help.verifyTitle(Help.java:161) at
> Modules.Help.GUI(Help.java:152) at Modules.Help.main(Help.java:29)
It is checking everything proper but not sure why throwing exception? How can I print message like "Title does not match" instead of this exception.
Write this:
if (!Objects.equals(actualTitle, expectedTitle))
System.out.println("Title doesn't match.");
But why would you want to do that?
Selenium tests inform you when something is not as expected, automatically. Throwing an AssertError means failure, and that failure can be displayed nicely to humans. When you use System.out.println, you just print something, but the program continues as if there were no error.
That is expected behavior of JNunit! It will always throw exception when assert failed. Here is description of the method assertThat:
Asserts that actual satisfies the condition specified by matcher. If
not, an AssertionError is thrown with information about the matcher
and failing value.
You can try/catch the Error then print the message that you want.
try {
assertThat("a", equalTo("a"));
System.out.println("Title matched");
}
catch(Error e) {
System.out.println("Title does not match");
}
You should try the try catch, have a look here: http://beginnersbook.com/2013/04/try-catch-in-java/ I think it could help you ;)
Just study the javadoc for assertThat:
Asserts that actual satisfies the condition specified by matcher. If not, an AssertionError is thrown with information about the matcher and failing value.
The point is that when you are running with JUnit, the exception is catched; and translated to some nice printout. So, when you are working outside of a JUnit #Test; well; then some other code needs to try/catch ...

WebDriver + TestNG - How to handle test results

I'm quite new to WebDriver and TestNG framework. I've started with a project that does a regression test of an e-commerce website. I'm done with the login and registration and so on. But there is something that I don't quite understand.
Example, I have this easy code that searches for a product.
driver.get(url + "/k/k.aspx");
driver.findElement(By.id("q")).clear();
driver.findElement(By.id("q")).sendKeys("xxxx"); //TODO: Make this dynamic
driver.findElement(By.cssSelector("input.submit")).click();
Now I want to check if xxxx is represented on the page. This can be done with
webdriver.findElement(By.cssSelector("BODY")).getText().matches("^[\\s\\S]*xxxxxx[\\s\\S]*$")
I store this in a Boolean and check if its true or false.
Now to the question, based on this Boolean value I want to say that the test result is success or fail. How can I do that? What triggers a testNG test to fail?
TestNG or any other testing tool decides success or failure of a test based on assertion.
Assert.assertEquals(actualVal, expectedVal);
So if actualVal and expectedVal are same then test will pass else it will fail.
Similarly you will find other assertion options if you using any IDE like Eclipse.
If you want to stop your test execution based on the verification of that text value, then you can use Asserts. However, if you want to log the outcome of the test as a failure and carry on, you should try using soft assertions, which log the verification as passed or failed and continue with the test. Latest Testng comes equipped to handle this - info at Cedric's blog
write this code where your if condition fails
throw new RuntimeException("XXXX not found: ");
u can use throw exception, and each method which will cal this meth should also throw Excetion after method name or you can use try catch. sample:
protected Boolean AssertIsCorrectURL(String exedctedURL) throws Exception {
String errMsg = String.format("Actual URL page: '%s'. Expected URL page: '%s'",
this.driver.getCurrentUrl(), exedctedURL);
throw new Exception(errMsg);
}
You can do this.
boolean result = webdriver.findElement(By.cssSelector("BODY")).getText().matches("^[\s\S]xxxxxx[\s\S]$")
Assert.assertTrue(result);

Categories