ib23
ib23

Reputation: 95

Overriding TestNG annotation for certain test

here is the question.

I have a class that has an @AfterMethod method, the method applies for all my test methods except two tests(The business case is that it deletes something I don't want to be deleted after each method). Is there a way to ignore the @afterMethod for a specific test method ?

I have a solution but it's not that elegant, any other soultions would be highly apreciated.

One way to do this is by having a child class that extends the parent class, and inside the class I can override the @AfterMethod, but I would prefer to have all the tests in the same place.

Upvotes: 0

Views: 1741

Answers (1)

Krishnan Mahadevan
Krishnan Mahadevan

Reputation: 14736

The easiest way of doing this would be as below:

  • Define a custom annotation which when used states that configuration for a particular test method needs to be skipped.
  • Annotate all @Test methods for which config is to be skipped using this new annotation.
  • Within your configuration method, check if the incoming method has this annotation and if yes skip execution.

Below is a sample that shows all of this in action.

Marker annotation that indicates that a configuration method is to be skipped.

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target({METHOD, TYPE})
public @interface SkipConfiguration {

}

Sample test class

import java.lang.reflect.Method;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;

public class TestClassSample {

  @Test
  @SkipConfiguration
  public void foo() {}

  @Test
  public void bar() {}

  @AfterMethod
  public void teardown(Method method) {
    SkipConfiguration skip = method.getAnnotation(SkipConfiguration.class);
    if (skip != null) {
      System.err.println("Skipping tear down for " + method.getName());
      return;
    }
    System.err.println("Running tear down for " + method.getName());
  }
}

Upvotes: 1

Related Questions