Reputation: 59
I am working on selenium and testNG with java.. I have some problem about this code:
Assert.assertEquals(webDriver.getCurrentUrl(), "http://google.com");
the question is how to create if else condition in assertEquals. like this
if( Assert.assertEquals(webDriver.getCurrentUrl(), "http://google.com"));
{
//do Nothing
}
else
{
// take screenshoot
}
any idea guys?
Upvotes: 1
Views: 37199
Reputation: 8531
If an assert fails, it throws an assertionError. You need to catch the AssertionError and in the catch capture the screenshot.
try{
Assert.assertEquals(...,...);
}catch(AssertionError e){
Log error;
Takescreenshot;
}
Upvotes: 7
Reputation: 50809
If the condition in Assert.assertEquals()
is false, for example Assert.assertEquals("qwerty", "asdfgh")
, the test will terminate, so there is no point to put it in if
statement.
If you want the test to to take screenshot in failure you can write your on assertEquals
implementation
public static class Assert
{
public static void assertEquals(Object actualResult, Object expectedResult, boolean stopOnError = true)
{
if (!expectedResult.equals(actualResult))
{
// take screenshot
if (stopOnError)
{
throw new Exception();
}
}
}
}
And then simply do
Assert.assertEquals(webDriver.getCurrentUrl(), "http://google.com"));
You can also change stopOnError
to false to prevent test termination when they are not equal.
If you don't want the test to end if the URL is wrong simply do
if (!webDriver.getCurrentUrl().equals("http://google.com"))
{
// take screenshot
}
Upvotes: 0
Reputation: 55
string url = webDriver.getCurrentUrl();
if(url == "http://google.com")
{
// take screenshoot
}
Assert.assertEquals(url, "http://google.com")
Upvotes: 0