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?
Making the inner class static works for me.
In JUnit 5, you simply mark non-static inner classes as
@Nested
:I think some of the answers might be for older versions of JUnit. In JUnit 4 this worked for me :
You should annontate your class with
@RunWith(Enclosed.class)
, and like others said, declare the inner classes as static:I've had success with Nitor Creation's Nested Runner as well.
How to use Nitor Creation's Nested Runner
There is a post explaining it here:
Add this dependency:
And a
@RunWith
to your test:PS: The example code has been taken and modified from the above blog post