Open In App

Introduction to JUnit 5

Last Updated : 03 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

JUnit is a Testing Framework. The Junit 5 is the latest version of the testing framework, and it has a lot of features when compared with Junit 4. The JUnit 5 version has three different modules for defining and performing different functionalities in testing. The components are:

  • JUnit Platform
  • JUnit Jupiter
  • JUnit Vintage

These three components play an important role in writing test cases for a software application. Now we will discuss each component in simple words.

JUnit Platform

In Software Industries, The Testing team designs and develops different types of test cases for checking the quality of the application. This means they test application functionality and Behavior in different conditions. After the Test cases are Developed, where we run those test cases. The Answer is, In Java If we want to run the test cases, we need JVM. So, the JUnit Platform provides a launching mechanism for testing frameworks on the JVM.

JUnit Jupiter

The second component in Junit 5 is JUnit Jupiter. This component provides new programming techniques for developing the test cases in JUnit 5.

JUnit Vintage

The Third component is JUnit Vintage in JUnit 5. The JUnit Vintage functionality is different from the above Two. Before JUnit 5, The Tester uses JUnit 4, JUnit 3, or some other Versions. But nowadays everybody shows interest in JUnit 5 for developing test cases. The Main functionality of JUnit Vintage is allowing JUnit 3 and JUnit 4 Test cases on the JUnit 5 Platform.

The JUnit Provides a lot of features when compared with JUnit 4. If want to learn JUnit 5 then we need to know some basics of the JUnit 5 Framework. Now I provide the basic information about JUnit 5. The basics of JUnit 5 are,

  • Annotations
  • Test Life cycle methods
  • Assertions
  • Assumptions
  • Parameterized Test
  • Dynamic Tests
  • Tagging and Filtering

Annotations

The JUnit 5 framework uses different Annotations based on the test case design. Mostly in JUnit 5 @Test, @BeforeEach, @AfterEach, @BeforeAll, @AfterAll these annotations are used. Basically, Annotations provides supplement information about the program in java. Annotations are always start with “@” symbol. ( reference ).

Test Life cycle methods

The JUnit 5 life cycle methods are annotated methods which are always start with @ symbol, these methods are executed at specific point in the test life cycle. The Life cycle methods are,

  • @BeforeEach, This Annotated method executes before each test method in the test class.
  • @AfterEach, This Annotated method executes after each test method in the test class, by sending signals to JUnit
  • @BeforeAll, this send signals to JUnit, Like the annotated method should be executed once before all test cased in the class.
  • @AfterAll, this annotation send signal to JUnit that is this annotated method should be run after all test cases are executed in the class.

Assertions

The JUnit 5 provides different methods in Assertions class for checking the expected Result by using @assertEquals, @assertTrue, @assertNotNull. The @assertEquals checks whether the expected result equals to actual test result or not. @assertTrue is used to test the condition is true or false. @assertNotNull is used to check the object is null or not.

Example of Assertions:

Java




//Java program to demonstrate JUnit Assertion
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
  
public class MyTest {
    @Test
    void exampleTest() {
        int result = someMethod();
        Assertions.assertEquals(42, result, "The result should be 42");
    }
    private int someMethod() {
        return 42;
    }
}


For above code the test case passed successfully.

Assumptions

Assumptions in JUnit 5 provides a good way for checking the test cases conditionally based on preconditions and one more is if Assumptions is failed then it is marked as skipped rather then failed. Means Assumptions are used to when you want to skip a test then we use Assumptions in JUnit 5.

  • assumeTrue() this method is used to skip the test when a specified condition is not true for assumeTrue or not false for assumeFalse.
  • assumingThat() this method is allowing us, to execute a block of code based on a Boolean Assumptions, If the Assumptions is false the block is skipped.

Example of Assumptions:

Java




//Java program to demonstrate JUnit Assumption
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test;
  
public class MyTest {
  
    @Test
    void exampleTest() {
        boolean condition = "true".equalsIgnoreCase(System.getProperty("runTest"));
        Assumptions.assumeTrue(condition, "Skipping the test because the condition is not met");
        int result = someMethod();
        Assertions.assertEquals(42, result, "The result should be 42");
    }
  
    private int someMethod() {
        return 42;
    }
}


Parameterized Test

This Parameterized Test is used to test a Test case with different parameters for this we use @ParameterizedTest annotations.

Example of Parameterized Test:

Java




//Java program to demonstrate parameterized test
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
  
public class MyParameterizedTest {
  
    @ParameterizedTest
    @ValueSource(ints = {1, 2, 3, 4, 5})
    void testSquare(int value) {
        int result = square(value);
        assertEquals(value * value, result, "Square calculation is incorrect");
    }
  
    private int square(int number) {
        return number * number;
    }
}


Dynamic Tests

For creating Dynamic Tests in Run time by using @TestFactory annotation. This TestFactory provides a feature to create dynamic test case in the run time of the Application.

Example of Dynamic Test:

Java




//Java program to demonstrate Dynamic Test
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import org.junit.jupiter.api.function.Executable;
  
import java.util.Collection;
import java.util.stream.Stream;
  
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.DynamicTest.dynamicTest;
  
public class MyDynamicTest {
  
    @TestFactory
    Collection<DynamicTest> dynamicTestsFromStream() {
        return generateTestCases().map(input ->
                dynamicTest("Test " + input, () -> assertTrue(input % 2 == 0))
        ).toList();
    }
  
    private Stream<Integer> generateTestCases() {
        return Stream.of(2, 4, 6, 8, 10);
    }
}


Tagging and Filtering

We can tag our test cases by using @tag annotation in the JUnit 5. Simply the Tags are labels for categorize the test cases. And Filter is used to filter and run the test cases by using the Tags.

Example of Tagging and Filtering:

Java




//Java program to demonstrate Tagging and Filtering
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
  
import static org.junit.jupiter.api.Assertions.assertTrue;
  
public class TaggedTests {
  
    @Test
    @Tag("fast")
    void fastTest() {
        assertTrue(true, "This is a fast test");
    }
  
    @Test
    @Tag("slow")
    void slowTest() {
        assertTrue(true, "This is a slow test");
    }
  
    @Test
    @Tag("fast")
    @Tag("integration")
    void fastIntegrationTest() {
        assertTrue(true, "This is a fast integration test");
    }
}


@AfterAll, @AfterEach and @BeforeAll, @BeforeEach

Here we will understand one example for sum of two numbers by using such as @BeforeAll, @AfterAll, @BeforeEach, @AfterEach Annotations.

Java




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.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
  
public class MySingleTestClass {
  
    private int num1;
    private int num2;
  
      
    @BeforeAll
    static void setupBeforeAll() {
        System.out.println("Before all tests");
    }
  
      
    @AfterAll
    static void cleanupAfterAll() {
        System.out.println("After all tests");
    }
  
     
    @BeforeEach
    void setupBeforeEach() {
        System.out.println("Before each test");
        num1 = 2;
        num2 = 3;
    }
  
      
    @AfterEach
    void cleanupAfterEach() {
        System.out.println("After each test");
    }
  
  
    @Test
    void testAddTwoNumbers() {
        System.out.println("Adding two numbers");
        int result = num1 + num2;
        assertEquals(5, result, "the sum should be 5");
    }
  
    @Test
    void testAnotherMethod() {
        System.out.println("Another test method");
          
    }
}


Conclusion

Before going to JUnit 5 we should know basic of testing methods as well as knowledge on JUnit 4. And we should know about Annotation in Spring Boot for testing related functionalities. Then only we can understand the functionality of JUnit 5 Testing Framework otherwise it is little bit difficult to understand It’s Functionality. But The JUnit 5 provides lot of features for application testing purpose when comparing with other frameworks.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads