Test cases in inner classes with JUnit

Svish picture Svish · Jan 6, 2012 · Viewed 37.5k times · Source

I read about Structuring Unit Tests with having a test class per class and an inner class per method. Figured that seemed like a handy way to organize the tests, so I tried it in our Java project. However, the tests in the inner classes doesn't seem to be picked up at all.

I did it roughly like this:

public class DogTests
{
    public class BarkTests
    {
        @Test
        public void quietBark_IsAtLeastAudible() { }

        @Test
        public void loudBark_ScaresAveragePerson() { }
    }

    public class EatTests
    {
        @Test
        public void normalFood_IsEaten() { }

        @Test
        public void badFood_ThrowsFit() { }
    }
}

Does JUnit not support this, or am I just doing it wrong?

Answer

Theodor picture Theodor · Mar 1, 2013

You should annontate your class with @RunWith(Enclosed.class), and like others said, declare the inner classes as static:

@RunWith(Enclosed.class)
public class DogTests
  {
  public static class BarkTests
  {
    @Test
    public void quietBark_IsAtLeastAudible() { }

    @Test
    public void loudBark_ScaresAveragePerson() { }
  }

  public static class EatTests
  {
    @Test
    public void normalFood_IsEaten() { }

    @Test
    public void badFood_ThrowsFit() { }
  }
}