You’re using JUnit Wrong

junit interview question

junit interview question

During pairing interviews we often chuck this little JUnit interview question into the mix:

import org.junit.Test;

public class ATest {
    private int testInstance = 0;


    @Test
    public void aTest() throws Exception {
        testInstance++;
        System.out.println(testInstance);
    }

    @Test
    public void anotherTest() throws Exception {
        testInstance++;
        System.out.println(testInstance);

    }

    @Test
    public void aSecondTest() throws Exception {
        testInstance++;
        System.out.println(testInstance);

    }
}

We have three tests and in each test we increment an integer by 1.  What is the expected output?

Click to reveal the answer!
If you guessed 3 then you’re wrong! The reason we bring this up during a pair programming interview is because candidates will often use a teardown method to null or reset some data objects so that they’re back to their original state for the next test. You don’t need to do this! Each run of the test JUnit will create a brand new instance of the test. As a result the output of the above is “1” each time. To further proove the point, here is the output again but this time also printing out the object.junit output

As you can see, each time there is a brand new instance created.

 

Be the first to leave a comment. Don’t be shy.

Join the Discussion

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>