JUnit 4 Class LifeCycle | What Runs When Annotations?

JUnit 4 – Which test methods run? When?

JUnit 4 has a simple run cycle for test classes based on annotations.
The four key annotations are

  1. @BeforeClass
  2. @AfterClass
  3. @Before
  4. @After

JUnit 4 – What Runs When Lifecycle

JUnit 4 will now execute these methods with a lifecycle that runs in this order

  1. setupOnlyOnce() — this method must be static
  2. setUp()
  3. testAFewLinesHere() — the first test method
  4. tearDown()
  5. setUp()
  6. testAFewLinesThere() — the second test method
  7. tearDown()
  8. tearDownOnlyOnce() — this method must be static

That is the order JUnit4 will run your tests. See the Java JUnit test code below.

Note that it is best to avoid the one initializers. Use it only when necessary. If you need to use it – then maybe look to see if you can refactor your code so that you do not need to use them.

It is common practise to do one-time initializers if the setup is extremely resource intensive (taking more than 1 minute).

My Unit Test is Fat

If your unit test is really fat , know that there is a thin skeletal test in there just dying to get out.

Unit tests are born to be lightweight.

JUnit (Java) Test Class Skeleton

Note that the list initializer is run before each test method – it is run twice.

    public class BuildBusinessWebsitesTest {
    
        private List stringMeAlong = new ArrayList();

        @BeforeClass
        public static void setupOnlyOnce() {
            // download big file
            // open big file
            // check it has what we need
            // close big file handle
        }

        @AfterClass
         public static void tearDownOnlyOnce() {
            // delete big file
        }

        @Before
        public void setUp() {
            // read the first 100 lines of big file into a list
        }
	
        @After
        public void tearDown() {
            // purge the list
        }

        @Test
        public void testAFewLinesHere() {
            // assert some things
        }
	
        @Test
        public void testAFewLinesThere() {
             // assert some other things
        }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *