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
Unfortunately you have to code this logic. JUnit does not have such feature. Generally you have 2 solutions:
@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.
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();
}
};
}
If you are using Mockito, particularly Mockito 3.0, all stubbings will be "strict" and be validated by default.
You could use the Mockito lenient() method.
More here: https://www.baeldung.com/mockito-unnecessary-stubbing-exception#lenient-stubbing
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(){}
}
}
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.
I was looking for a solution to this problem and bumped into this question. As an update, in JUnit 5 this can be easily accomplished now with the use of the @Nested annotation.