devoured elysium
devoured elysium

Reputation: 105037

Creating an annotation of my own to extend JUnit4 behaviour

I've been looking for resources on how to extend JUnit4 with my own annotations.

I'd like to be able to define a @ExpectedProblem with which I could label some of my tests. I've seen there seems to be some material on the net on how to extend TestNG, but I could fine none to extend JUnit4.

Has anyone here extended JUnit4 in the past?

Thanks

Upvotes: 0

Views: 1161

Answers (2)

Alistair A. Israel
Alistair A. Israel

Reputation: 6567

Depending on what you want your @ExpectedProblem annotation to do, another option is to create a @Rule.

This requires JUnit 4.7+, but should be simpler than implementing your own Runner.

For instance, if you want an annotation to say, "this test should throw an exception" then you'll want to take a look at the @ExpectedException rule. Even if that's not enough for your needs it can provide a good starting point for implementing your own rule.

Upvotes: 2

pap
pap

Reputation: 27614

Basic approach is to create your own class runner. For instance, by extending the org.junit.runners.ParentRunner or org.junit.runners.BlockJUnit4ClassRunner classes. You would then annotate your test class with @RunWith(<your class runner>.class). In your runner, you could then analyze the test-class to check for annotations and take appropriate actions etc. Found this googling: http://tedyoung.me/2011/01/23/junit-runtime-tests-custom-runners/

This is how Spring modeled their JUnit support, using the org.springframework.test.context.junit4.SpringJUnit4ClassRunner

Upvotes: 1

Related Questions