Question

Are there any documented conventions for the order in which method types are placed within JUnit tests? I typically have the following order: @Before, @Test, @After; I have also seen: @Test, @Before, @After.

Example methods:

public class SandBoxTest {
    SandBox sand;

    @BeforeClass
    public void classSetup() { }

    @Before
    public void given() { }

    @Test
    public void shouldTestThis() { }

    // support method
    private boolean doStuff() {
        return true;
    }

    @Test
    public void shouldTestThat() { }

    @After
    public void cleanUp() { }

    @AfterClass
    public void classCleanUp() { }
}

If there is a 'standard' convention, please provide references.

Was it helpful?

Solution

I think there is no such a coding convention but don't forget about the @Rule annotation.

http://blog.schauderhaft.de/2009/10/04/junit-rules/

OTHER TIPS

I had this discussion with one of my colleagues. I was arguing for the order @BeforeClass, @Before, @After, @AfterClass, and then all the @Test, whereas he wanted the order to be @BeforeClass, @Before, all the @Test, and then @After, @AfterClass.

My arguments for having the setUp and tearDown methods at the top were:

  • You can easily see the conditions of the tests when you enter the test class.
  • Many times the tearDown is a reflection of something done in the setUp. In that case it can be useful to have them both on screen to make it easier to see that they match each other.
  • You dont have to scroll to the bottom to find out if there is any tearDown (which we usually don't have in the tests classes in our project).

His argument for having the tests in between the setUp and tearDown methods was that it was the logical order, which also reflects the order in which the methods are excecuted.

We searched for a convention on the Internet but didn't find any so in the end we agreed to disagree and decided that both orders were accepted in the project.

This may not be a straight answer to the question but I thought I'd share our discussion with others facing the same decision.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top