Is it possible to run a JUnit @Test
method in a class that has a method annotated with @Before
, but to ignore the @Before
method only for this test?
Edit: I am interested if JUnit supports this functionality, not workarounds. I am aware of workarounds like moving the test(s) in another class or removing the annotation and manually calling setUp()
in each test method.
Suppose in a class there are 30 tests, and for 29 of them @Before
really simplifies the testing initialization, but for one (or more than one) of them is useless/it complicates things.
public class MyTestClass {
@Before
public void setUp() {
//setup logic
}
@Test
public void test1() {
//[...]
}
@Test
public void test2() {
//[...]
}
//more tests here
@Test(ignoreBefore = true, ignoreAfter = true //false by default)
//something equivalent to this
public void test20() {
//[...]
}
}
You can do this with a TestRule. See my answer to Exclude individual test from 'before' method in JUnit. Basically, implement ExternalResource, and in the apply method, check if there is a specific annotation on the method, and if there is, don't run the before/after method. You'll have to specifically call the before/after from your rule though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With