Exclude individual test from 'before' method in JUnit

Consider using the @Enclosed runner to allow you to have two inner test classes. One with the required @Before method, the other without.

Enclosed

@RunWith(Enclosed.class)
public class Outer{

    public static class Inner1{

     @Before public void setup(){}

     @Test public void test1(){}
    }

  public static class Inner2{

   // include or not the setup
   @Before public void setup2(){}

   @Test public void test2(){}
  }

}

Unfortunately you have to code this logic. JUnit does not have such feature. Generally you have 2 solutions:

  1. Just separate test case to 2 test cases: one that contains tests that require "before" running and second that contains tests that do not require this.
  2. Implement your own test running and annotate your test to use it. Create your own annotation @RequiresBefore and mark tests that need this with this annotation. The test runner will parse the annotation and decide whether to run "before" method or not.

The second solution is clearer. The first is simpler. This is up to you to chose one of them.


This question has been asked a while ago, nevertheless, I would like to share my solution:

  1. Annotate the desired method with @Tag("skipBeforeEach")

  2. In your setup() method:

    @BeforeEach
    void setup(final TestInfo info) {
    final Set<String> testTags = info.getTags();
    if(testTags.stream()
               .filter(tag->tag.equals("skipBeforeEach"))
               .findFirst()
               .isPresent()){
    return;
    }
    // do your stuff
    }```
    
    

You can do this with a TestRule. You mark the test that you want to skip the before with an annotation of some description, and then, in the apply method in the TestRule, you can test for that annotation and do what you want, something like:

public Statement apply(final Statement base, final Description description) {
  return new Statement() {
    @Override
    public void evaluate() throws Throwable {
      if (description.getAnnotation(DontRunBefore.class) == null) {
        // run the before method here
      }

      base.evaluate();
    }
  };
}