Tuesday, 13 July 2021

junit5: @Nested: Execute tests of inner classes

Simply annotate inner classes with @Nested annotation, so all the test methods in the inner class gets executed.

 

NestedDemo.java

package com.sample.app;

import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;

public class NestedDemo {

  @Test
  void a() {
    assertTrue(true);
  }

  @Nested
  class InnerClass1 {
    @Test
    void innerClass1_a() {
      assertTrue(true);
    }

    @Nested
    class InnerClass2 {
      @Test
      void innerClass2_a() {
        assertTrue(true);
      }
    }
  }

}

 

How to run the tests?

Right click on 'NestedDemo.java' -> Run As -> Junit Test.


Select NestedDemo class and click on OK button.


From the above image, you can confirm that the tests in nested classes gets executed.

 

Since @BeforeAll and @AfterAll are static methods, these will not get evaluated for @Nested classes. On the otherhand, @BeforeEach and @AfterEach methods get inherited in @Nested classes.

 

You can confirm the same with below example.

 

NestedDemo1.java

package com.sample.app;

import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;

public class NestedDemo1 {

  @BeforeAll
  static void systemSetup() {
    System.out.println("Setting up System");
  }

  @BeforeEach
  void filesSetup() {
    System.out.println("\nSetting up dummmy files for test case");
  }

  @AfterEach
  void filesClean() {
    System.out.println("Delete dummy files");
  }

  @AfterAll
  static void systemCleanup() {
    System.out.println("\nCleaning up System");
  }

  @Test
  void a() {
    System.out.println("Executing test mehthod a()");
    assertTrue(true);
  }

  @Nested
  class InnerClass1 {
    @Test
    void innerClass1_a() {
      System.out.println("Executing test mehthod innerClass1_a()");
      assertTrue(true);
    }

  }
}


Run NestedDemo1.java, you will see below messages in console.

Setting up System

Setting up dummmy files for test case
Executing test mehthod a()
Delete dummy files

Setting up dummmy files for test case
Executing test mehthod innerClass1_a()
Delete dummy files

Cleaning up System

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment