July 28, 2009

Unit testing with Maven and NetBeans 6.7

The JUnit test runner has improved a lot in NetBeans 6.7. Now we can run single test methods and we get better feedback.

Let's start with a simple Maven project. We go to File | New Project | Maven | Maven Project. We select the Maven Quickstart Archetype (1.0) from the list of archetypes. We fill in all required fields and press the OK button. NetBeans creates a new Maven project in the IDE. The Quickstart Archetype already created a JUnit test class for us, so we can immediately see the new NetBeans JUnit testrunner. We go to Run | Test Project. And in the Test Results tab we get the good news that alls tests have passed:

Okay for this example it is pretty obvious, but in NetBeans 6.7 we can right-click on the method name and select Run Again. Now only this method is tested and not the whole class:

We can imagine this is especially useful for methods that do not run successful. Let's add a test method that will fail. We open the AppTest class and add the following method, which will fail during test:

public void testFailure() {
    fail("Deliberate fail...");

When we test the class again our Test Results output has changed:

The progress bar is no longer green, we have a 50% green and 50% red part. We also see the testFailure method has failed. The good thing is we can only run the failed method again by right-clicking on the method and selecting Run Again. To go directly to the source code we must right-click on the method and select Go to Source. NetBeans opens the source code file and jumps to the right position in the editor. The Go to Source on a method only works when we create a NetBeans Java project, if we use a Maven project only if we select Go to Source on the class name we jump right to the source code of the test class.