How do I skip a before method in a specific test?

Viewed 386

I have a POM framework. In the BaseTest class I have the following @BeforeMethod

@BeforeMethod(alwaysRun = true)
@Parameters("url")
public void goHome(String URL) {
    driver.get(URL);
    this.setInventoryPage(
            new LoginPage(driver)
                    .setUsername(this.getSauceUserName())
                    .setPassword(this.getSaucePassword())
                    .clickLoginButton());
}

That method includes the login steps so I don't have to add the same line of code in all the tests. Now, the issue is that I have the following 2 test scenarios in the LoginTests class (locked account and wrong credentials). My LoginTests class extends BaseTests class.

@Test(groups = {"Login", "Negative" })
public void lockedCredentials(){
    LoginPage loginPage = new LoginPage(driver);
    loginPage.setUsername("wrong_user");
    loginPage.setPassword("secret_sauce");
    loginPage.clickLoginButton();
    assertTrue(loginPage.getErrorMessageText()
                    .contains("Epic sadface: Sorry, this user has been locked out."),
            "Credentials are not locked!");
}

@Test(groups = {"Login", "Negative"})
public void invalidCredentials(){
    LoginPage loginPage = new LoginPage(driver);
    loginPage.setUsername("wrong_user");
    loginPage.setPassword("wrong_pass");
    loginPage.clickLoginButton();
    assertTrue(loginPage.getErrorMessageText()
                    .contains("Epic sadface: Username and password do not match any user in this service"),
            "The credentials entered are valid!");
}

My question is how do I ignore the above @BeforeMethod for the above 2 tests scenarios (just for locked account and wrong credentials)?

Note: I'm using TestNG.

1 Answers

There is no way to skip @BeforeMethod.

A workaround here could be moving those two methods to the subclass of your Test and overriding the goHome method.

Example:

public abstract class LoginTest {
    @BeforeMethod(alwaysRun = true)
    public void goHome() {
        System.out.println("Going Home...");
    }
}

class NegativeLoginTest extends LoginTest {
    @Override
    public void goHome() {
        // do nothing
    }

    @Test(groups = {"Login", "Negative"})
    public void lockedCredentials() {
        System.out.println("Locked Credentials");
    }

    @Test(groups = {"Login", "Negative"})
    public void invalidCredentials() {
        System.out.println("Invalid Credentials");
    }
}


class PositiveLoginTest extends LoginTest {
    @Test(groups = {"Login", "Positive" })
    public void correctCredentials(){
        System.out.println("Correct Credentials");
    }
}

There are three classes in the example:

  • LoginTest - base class for Login tests
  • PositiveLoginTest - all the tests call LoginTest#goHome before each method
  • NegativeLoginTest - owerrides goHome method, so LoginTest#goHome won't be called
Related