Question

I have a base class for all my tests with defined @BeforeMethod which fits to most of the tests (I am testing admin UI so I want to usually log in as an administrator before test and log out after it) - but sometimes I would like to either skip this method or override it with different one in the class which is extending my base class.

public class AbstractWebDriverTest {

    @BeforeMethod
    public void preparePage() {
        driver.get("somePage");
        signInAsAdmin();
    }

}

public class TestConfigWithOtherUser extends AbstractWebDriverTest {

    //now I want to skip before method and sign as a different user instead

    @Test
    public void someTestWithDifferentUser() { }

}

So I guess I could solve this with using groups somehow but is there a way how to override the init method?

No correct solution

OTHER TIPS

I would go either by grouping tests as you stated in your question or by exception. If just few cases are the exception, your test in that cases must expect, that you start as admin. My idea in Java Pseudocode:

 @Test
 public void someTestWithDifferentUser() {
  logout();
  logInAsDifferentUser();
  doSomeStuff();
 }

My other Idea is to introduce User class which could look like this:

public class User{
  private String username;
  private String password;

  public User(String username, String password){
    this.username = username;
    this.password = password;
  }

  public String getUsername(){
    return username;
  }   

  public String getPassword(){
    return password;
  }

}

Then, in your tests you would have one global variable:

public static final User DEFAULT_USER = new User("admin","AdminSecretPassword");

and your tests would look like this:

@Test
public void doAdminStuff(){
 loginAsUser(DEFAULT_USER);
 doAdminStuff;
}

@Test
public void doUserStuff(){
 loginAsUser(new User("testytester","testytest"));
 doUserStuff();
}

Where the @BeforeMethod would avoid the login completly.

You can use Listeners interface to override default behaviour. Refer this post which had a similar requirement to yours.

public class SkipLoginMethodListener implements IInvokedMethodListener {

private static final String SKIP_GROUP = "loginMethod";

@Override
public void beforeInvocation(IInvokedMethod invokedMethod, ITestResult testResult) {
    ITestNGMethod method = invokedMethod.getTestMethod();
    if (method.isAfterMethodConfiguration() || method.isBeforeMethodConfiguration()) {
        for (String group : method.getGroups()) {
            if (group.equals(SKIP_GROUP)) {
                System.out.println("skipped " + method.getMethodName());
                throw new SkipException("Configuration of the method " + method.getMethodName() + " skipped");
            }
        }
    }
}

@Override
public void afterInvocation(IInvokedMethod method, ITestResult testResult) {
}

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top