RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Get Acquainted with the New Advanced Features of JUnit 4

Learn how to migrate from JUnit 3.8 to JUnit 4. Discover version 4's new features, including extensive use of annotations, and find out the status on IDE integration.

oes anybody need an introduction on JUnit? No? OK, so I'll assume that you know this Java unit testing framework created by Kent Beck and Erich Gamma and skip the introduction. Instead I will focus on the migration process from JUnit 3.8 to the latest version, JUnit 4, and its integration in IDEs and Ant.

JUnit 4 is a completely different API from the versions that came before it and depends on new features of Java 5.0 (annotations, static import…). As you'll see, JUnit 4 is simpler, richer, and easier to use and introduces more flexible initialization and cleanup, timeouts, and parameterized test cases.

Nothing beats a bit of code for clarification. I'll use an example that I can use to illustrate different test cases throughout the article: a calculator. The sample calculator is very simple, inefficient, and even has a few bugs; it only manipulates integers and stores the result in a static variable. Substract method does not return a valid result, multiply is not implemented yet, and it looks like there is a bug on the squareRoot method: It loops infinitely. These bugs will help illustrate the efficiency of the tests in JUnit 4. You can switch this calculator on and off and you can clear the result. Here is the code:

package calc;

public class Calculator {

    private static int result;          // Static variable where the result is stored

    public void add(int n) {
        result = result + n;

    public void substract(int n) {
        result = result - 1;          //Bug : should be result = result - n

    public void multiply(int n) {}     //Not implemented yet

    public void divide(int n) {
        result = result / n;

    public void square(int n) {
        result = n * n;

    public void squareRoot(int n) {
        for (; ;) ;                    //Bug : loops indefinitely

    public void clear() {               // Cleans the result
        result = 0;

    public void switchOn() {          // Swith on the screen, display "hello", beep
        result = 0;                    // and do other things that calculator do nowadays

    public void switchOff() { }	     // Display "bye bye", beep, switch off the screen

    public int getResult() {
        return result;

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date