Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test cases in inner classes with JUnit

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?

like image 365
Svish Avatar asked Jan 06 '12 13:01

Svish


People also ask

How do you write JUnit test cases for inner classes?

First, we have to add a new inner class called A to our test class and annotate the inner class with the @Nested annotation. After we have created the A class, we have to add one setup, teardown, and test method to the created inner class.

What is nested test?

Junit 5 nested tests is used to express the relationship among several groups of tests and to represent tests in hierarchy. @Nested annotation allows you to have an inner class in a test class and that is another test class.

Does JUnit run tests in parallel?

Once parallel test execution property is enabled, the JUnit Jupiter engine will execute tests in parallel according to the provided configuration with declared synchronization mechanisms.


1 Answers

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() { }   } } 
like image 87
Theodor Avatar answered Oct 08 '22 20:10

Theodor