Nelz's Blog

Mah blogginess

TestNG vs JUnit4

JUnit has done huge things for the programming community. It really helped to usher “The Age of Testing” into being. I will always say that. However, I have to say that when starting a new Java project, using TestNG is the right choice.

Here is how I see things happening:

  1. Project starts. Choose the ‘industry standard’ JUnit. Heck, let’s even go with JUnit 4 because it supports Java 5 Annotations.
  2. JUnit works great for unit tests.
  3. Hey, we want to write an integration test (talking to a db? setting up a Spring ApplicationContext?) as well. We’re already using JUnit, so let’s keep using it for the new integration tests too.
  4. Let’s write a second (and third; and more) integration test within JUnit just like that first one we wrote.
  5. Hey, why is the build taking so long? Oh, hey, JUnit is causing us to do some heavyweight operations for each individual tests. Is there some way to only do the heavy operations once per a suite of tests?
  6. Blogosphere says: “JUnit is a unit testing framework, it’s not meant for integration testing”; “You are doing it wrong”; “Sure you can do that, here’s the horrible atrocity of code that you need to implement to make it possible”.
  7. Find that TestNG has a richer lifecycle and can help with this integration test scenario, while still being easy to use for unit tests. Shake your fist at the air in impotent rage that you didn’t just start with TestNG.

I’ve personally seen this happen in at least 2 large projects.

I am currently in the “impotent rage” phase of the cycle. My original impetus to write this blog post was to say that someone(*) should write the class that combines the org.junit.runners.Suite functionality and Spring’s AbstractTransactionalJUnit4SpringContextTests.

Here’s the straight scoop: You are probably going to want to do some integration testing in addition to unit testing. TestNG may only be a bit different from JUnit, but it is just enough different in all the right ways to make it the tool you want to use.

(*) I know I should consider doing it. I will add it directly to the top of my “Things That Should Get Done But Won’t Ever See the Light of Day” list.