JUnit is probably part of 90% of all Java projects. And the exciting thing is, we’ll soon have JUnit 5 with Java 8 support. We’ve blogged about an improvement recently.
Back in JUnit 4 land, there’s this little trick that I can only recommend you put in all of your unit tests. Just add this little annotation here and you’ll be much more happy:
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
class MyTests {
...
}
What does it do? It’s simple. It fixes JUnit’s weird default of not defaulting to any testing order. Sure, not having any order in your tests might help accidentally discover some evil test inter-dependency. But usually, when you’re looking for individual tests and results, e.g. in your IDE, it’s just much much better to be able to visually scan the test suite and find the right method.
E.g. what do you prefer? This?
Or this?
Exactly. Finally, a useful annotation. Just put the following everywhere and help make this a slightly better world:
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
class MyTests {
...
}
8 thoughts on “Improve Your JUnit Experience with this Annotation”
Huh. I can’t decide (yet) if I love it or hate it. Or both.
Thanks for the news about Junit 5. Does anyone have a brief summary of what’s different between 4 and 5? I skimmed the documentation, and it’s interesting, but I’m surprised there’s no “diff”, so to speak.
Opt for both. This should really be fixed in the UI (e.g. Eclipse) but before we’ll wait until 2038 for this to be improved, let’s just use this weird hack :)
What’s different between 4 and 5? Package names. And assertThrows() which accepts lambdas. Here’s some more: https://redd.it/4ahyz5
Huh. I can’t decide (yet) if I love it or hate it. Or both.
Thanks for the news about Junit 5. Does anyone have a brief summary of what’s different between 4 and 5? I skimmed the documentation, and it’s interesting, but I’m surprised there’s no “diff”, so to speak.
Opt for both. This should really be fixed in the UI (e.g. Eclipse) but before we’ll wait until 2038 for this to be improved, let’s just use this weird hack :)
What’s different between 4 and 5? Package names. And assertThrows() which accepts lambdas. Here’s some more: https://redd.it/4ahyz5
If you use Spock you can run tests in the order they’re declared in the class by using the @Stepwise annotation.
They must have learned from the best ;)
IntelliJ has a button to do this. See https://www.jetbrains.com/help/idea/2016.1/viewing-and-exploring-test-results.html (It is not explicitly written, but you can see a screenshot with the button to do it there)
That’s great of course. Thanks for sharing!
Just a small note that this requires JUnit 4.11: https://github.com/junit-team/junit4/wiki/Test-execution-order
Yes, indeed. Thank you very much for the comment.