Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Junit @Test that ignores @Before/@After

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() {
        //[...]
    }

}
like image 393
Random42 Avatar asked Dec 14 '12 11:12

Random42


1 Answers

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.

like image 94
Matthew Farwell Avatar answered Oct 13 '22 22:10

Matthew Farwell