JBCP
JBCP

Reputation: 13475

In Junit4, How to change @Before behavior based on @Test annotations

I would like my @Before method to know the currently executing tests Annotations, so that the @Before method can do various things. Specifically, right now our @Before always does various initialization steps like reloading the database, etc. I would like to be able to write code like this:

@Before
void setUp() {
    if (testMethod.hasAnnotation(@NeedsDatabase)) {
        reloadDatabase();
    }
}

I guess one solution would be to use a @Rule for DB initialization, but this would be complicated to implement and our existing infrastructure already handles this in @setUp. We already have a custom Runner and all tests extend a shared base class, if that helps.

I tried to think of a way to do this, but I don't know what is available in JUnit4.

Upvotes: 2

Views: 449

Answers (2)

sbridges
sbridges

Reputation: 25140

You could use the @RunWith annotion, and create your own ParentRunner that scans for your @NeedsDatabase annotation and handles setup appropriately.

Upvotes: 2

Related Questions