Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Improve Your JUnit Experience with This Annotation

DZone's Guide to

Improve Your JUnit Experience with This Annotation

Bummed out that the order of your JUnit tests is all over the map? You're in luck! Check out this article to see how to make your testing life just a bit more manageable!

· Java Zone
Free Resource

Make it happen: rapid app development on Kubernetes as a managed service.

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 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 {
    ...
}

Tutorial: WordPress as distributed microservices on Kubernetes.

Topics:
java ,junit ,annotation ,tip

Published at DZone with permission of Lukas Eder, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}