Improve Your JUnit Experience with this Annotation

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?

junit-better

Or this?

junit-worse

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

  1. 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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s