Syafriadi Hidayat
Syafriadi Hidayat

Reputation: 59

if else condition on Assert.assertEquals selenium testNG

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

Answers (3)

niharika_neo
niharika_neo

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

Guy
Guy

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

Wael Said Emara
Wael Said Emara

Reputation: 55

string url = webDriver.getCurrentUrl();
if(url == "http://google.com")
{
    // take screenshoot
}

Assert.assertEquals(url, "http://google.com")

Upvotes: 0

Related Questions