Search code examples
seleniumselenium-webdriverselenium-chromedriverassert

How to Write Assert method in Selenium once and use multiple times to verify text?


How to write below Assert method to verify text/message once so I can use it in multiple test in Selenium.

String expectedMessage = "Name: Z to A";
String actualMessage = getTextFromElement(By.xpath("//option[contains(text(),'Name: Z to A')]"));
Assert.assertEquals("Error, message not displayed", expectedMessage, actualMessage);

Solution

  • You can make a util method like this

    public void verifyText(String actualMessage, String expectedMessage, String description) {
        Assert.assertEquals(actualMessage, expectedMessage, description);
    }
    

    and call it whenever you want in your project. like this

    verifyText(actualMessage, expectedMessage, "Error, message not displayed");
    

    Also, you can make this method as static in case you are not creating object of util class.

    If you are creating an object then possibly you can use object reference to call this method.