Exclude individual test from 'before' meth

2019-02-11 22:36发布

问题:

All tests in my test class execute a 'before' method (annotated with JUnit's @Before) before the execution of each test.

I need a particular test not to execute this before method.

Is there a way to do it?

回答1:

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.



回答2:

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();
    }
  };
}


回答3:

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(){}
  }

}


回答4:

One can also solve this by undoing what was done in @Before setup inside test case. This is how it may look,

@Before
public void setup() {
    TestDataSetupClass.setupTestData();
}

@Test
public void testServiceWithIgnoreCommonSetup() {
    TestDataSetupClass.unSet();
    //Perform Test
}

There will be pros and cons for solutions here. Minor con for this is, unnecessary cycle of setting and un-setting step. But goes well if one needs to do it for only a test case out of hundreds and avoid overhead of writing self AOP or maintaining multiple inner test classes.