Search code examples
javawebdriverassert

AssertTrue in try/catch


Please what exactly am i doing wrong.

I have checked and checked but all to no avail. I have also checked previous code but I am not getting an error so my code works fine but just slight error somewhere.

The code is running fine and assertTrue is behaving as expected but when I put it in the try/catch, I only get the log in the catch block, even when text was found.

I believe that if the assertTrue found the text, it should go to the next line of code in the try block and pass the test rather than the catch block. Don't get me wrong, I am not getting any error just that it's printing out the wrong message.

Code below including print out message in console.

public boolean verifyTextPresent(String value) throws Exception {

    Thread.sleep(5000);     
    try{
        boolean txtFound = driver.getPageSource().contains(value);
        log.log(value + " : text Found, .......continue");
        return txtFound;        
    }catch(Exception e)
    {
        log.log(value + " :NOT Found, check element again ot Contact developer.");
        return false;
    }   
}

public static void verifySignOutBtn() throws Exception
{
    log.header("VERIFY IF SIGN_OUT EXIST AND CLICKABLE.........");

    callMethod.myAccountPageNative(CONSTANTElements.SIGN_IN_LINK);
    Thread.sleep(2000);     

    log.header("LOCATE SIGN_OUT BTN, AND CLICK ......");
    callMethod.elementPresent_Click(By.cssSelector(CONSTANTElements.SIGN_OUT_BTN));
    Thread.sleep(4000);         

    log.header("VERIFY SIGN_OUT NAVIGATES TO HOME PAGE WHEN CLICKED......");        
    try{        
        Assert.assertTrue(callMethod.verifyTextPresent("SIGN IN"), "SIGN IN");          
        log.log("User Successfully Signed Out.......");
        log.log("Test Passed!...");
        //callMethod.close();
    }
    catch(Throwable e)
    {
        log.log("User NOT Successfully Signed Out.... Contact developer.");
        log.log("Test Failed!...");
        //callMethod.close();
    }
    callMethod.close();
}

}

Msg in console:
SIGN IN : text Found, .......continue
User NOT Successfully Signed Out.... Contact developer.
Test Failed!...

The confusing part is that why is it printing out the catch block instead of the next line in the try block?


Solution

  • The only possible explanation is that verifyTextPresent(String value) returns false (you never actually check the value of boolean txtFound) and assertTrue fails (throwing an AssertionError which is not handled well in your catch block). To find out, replace this

    log.log(value + " : text Found, .......continue");
    

    for example with this line

    log.log(value + " : text Found, ......." + txtFound);
    

    or just print the stacktrace in catch block.