Assertion issue in Java and Eclipse - java

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 ...

Related

Selenium assertEqual

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.

In selenium how to continue running a script even if it is failed

i have a form filling script
during the execution in any line (Step) if the test case is failed it is directly closing the browser .
ex: while filling the form if it couldn't find a element (Textbox or Checkbox) it throws an exception nosuchelements and directly closes the browser i am using assert (testNG) in my script
what i want is if the test case is failed anywhere middle i want the test case to continue its execution but in the report it should show that the test case is failed
in my code
String Jobvalue = driver.findElement(By.xpath("//label[#for='ctl00_ContentPlaceHolder1_RadPanelBar1_i0_chkColumns_5']")).getText();
Assert.assertEquals(Jobvalue, "Job Value ($)");
Reporter.log(Jobvalue+" Text Verification ---- Passed",true);
Assert will fail the test case if actual value is not equals to expected value
i want an alternate to assert or any code which continues executing the test case till the end and at reports it should show it is failed if the actual value is not equal to expected value
Santhosh, We need more info/code on what are you exactly trying.By assumption, here is my answer for your question.
Use validate() methods rather assert () in your test steps.
Any exception can be easily handled using try-catch.
try{
String Jobvalue = driver.findElement(By.xpath("//label[#for='ctl00_ContentPlaceHolder1_RadPanelBar1_i0_chkColumns_5']")).getText();
Assert.assertEquals(Jobvalue, "Job Value ($)");
}
catch()
{
//Write your code here about failing the test
}
If an Assert fails, it throws an AssertionError and that's why your program is stopped. You can use try/catch to handle the exception.
try{
Assert......
}catch(AssertionError e){
//handle the exception
}
Refer here for Assert documentation

Verify if a link is present or not

I'm trying to verify if a link is present or not -- but -- if it's not present, I want my script to continue executing (close the browser, etc).
The purpose of my script is to determine if a 'Delete Address' link is present or not. If it is, I click on the link and delete the address. This works fine. If the link is not present however, I just want to continue execution without triggering an exception. My code below triggers an exception if the link is not there.
Thanks for any help...
try {
String txt = driver.findElement(By.linkText("Delete Address")).getText().trim();
Assert.assertTrue(txt.equals("Delete Address"));
Alert javascriptprompt = driver.switchTo().alert();
javascriptprompt.accept();
} catch (NoSuchElementException e) {
}
I can see several options here
Do not use asserts in the test at all. In this case the test is marked as successful (if you caught exceptions)
If you want the lines after the findElement() call be executed you can
move all lines expect for findElement() out of the try {} clause
use the try {} catch {} finally {} construction and put to the finally {} clause all the code you want to be executed, no matter what happens in the try {}
If you want to avoid catching exception, you can create a listener class by implementing the interface ITestListener and in onTestFailure() obtain the exception using getThrowable()
String stackTraceString = Throwables.getStackTraceAsString(getCurrentTestResult().getThrowable());
Then, if the exception is NoSuchElementException then set test result to success
result.setStatus(ITestResult.SUCCESS);
setCurrentTestResult(result);
Another solution would be to use .findElements. It will return an empty collection, as opposed to throwing an exception, if there are no elements found with the given selector.

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

Anyone can tell me what's wrong with this pseudo code?

I am not familiar with JUnit so not sure if that's the problem of assertTrue(b_exception);, because if I put an System.out.println("something"); there, it would print out "something"... Thanks!!
Please note that it is pseudo code, focus on the logic.
b_exception = false;
try{
somethingThrowError();
}catch(Error e){
b_exception = true;
}
assertTrue(b_exception);
I don't know what the problem is with your code because you haven't stated how it fails to fulfill your expectations, but the correct idiom for testing that an exception is thrown is to use JUnit 4's annotations:
#Test(expected=SpecificError.class)
public void testError(){
somethingThrowError();
}
I can only guess that you are looking for this:
try{
somethingThrowError();
fail("Exception expected");
}catch(AsSpecificAsPossibleException e){
//should happen, OK
//optionally assert exception message, etc.
}
Also note that catching an Error is a bad idea, use as specific exception as you can.
UPDATE: #Michael Borgwardt's answer is actually even better, but only if there is nothing except a single line in your test (nothing else that can throw). Also #Test(expected does not allow you to perform extra exception message assertions (but should you?)
Not sure what you think is wrong with that code.
The assertTrue will always be executed, as will the System.out.println.
It - the assertTrue - will signal an error if the argument is not true, or "pass the test" if the argument is true.
Maybe you should use System.out.println("b_exception = " + b_exception); to see what is happening.

Categories