How do I require JUnit tests to implement the @ BeforeClass / @ AfterClass abstract method?

As a heavy user of TestNG, this is not a problem since the methods @{Before,After}Class

are not static

...

But JUnit does.

And that's quite a problem for what I'm doing right now.

I am writing assertions for java.nio.file.Path for assertj which uses JUnit 4.x for tests. Some statements require me to initialize a FileSystem

(a memoryfs , to be precise) in order to test them; such a filesystem should ideally be initialized at the test class level and not at the test level. And depending on the testing class, I need to initialize the contents of this filesystem differently.

Currently, however, I use @Before

/ @After

, since I don't know better ...

Again, with TestNG, not a problem as @{Before,After}Class

they are not static. So how do you do this with JUnit? ...

+3


source to share


1 answer


You can create a rule class for your initialization:

public class Resource extends ExternalResource {
    protected void before() {
        // ...
    }

    protected void after() {
        // ...
    }
}

      

and then specify it in each test:



@ClassRule public static Resource resource = new Resource();

      

Any customization for each test can be done by creating an anonymous inner class resource and overriding methods or passing parameters to its constructor.

If you have a generic base class, you can put it there resource

and then only declare it in the subclasses you need to customize. In junit, class rules in subclasses override class rules in the parent class of the same name.

+3


source







All Articles