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. JUnit 5, also known as JUnit Jupiter. It introduces several new features and improvements over its predecessor, JUnit 4, making it more powerful and flexible for writing and running tests.
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
Maven Dependency for JUnit 5
To use JUnit 5 with Maven, you need to add the following dependencies to your pom.xml
:
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.9.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>5.9.3</version>
<scope>test</scope>
</dependency>
Gradle Dependency for JUnit 5
To use JUnit 5 with Gradle, you need to add the following dependencies to your build.gradle
:
testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.9.3'
testImplementation 'org.junit.vintage:junit-vintage-engine:5.9.3'
Annotations
The JUnit 5 framework uses different Annotations based on the test case design. Mostly in JUnit 5 @Test, @BeforeEach, @AfterEach, @BeforeAll, @AfterAll, @DisplayName, @Disabled
these annotations are used. Basically, Annotations provides supplement information about the program in java. Annotations are always start with "@" symbol. ( reference ).
@Test
: Marks a method as a test method.@BeforeEach
: Indicates that the annotated method should be executed before each test.@AfterEach
: Indicates that the annotated method should be executed after each test.@BeforeAll
: Indicates that the annotated method should be executed before all tests in the test class.@AfterAll
: Indicates that the annotated method should be executed after all tests in the test class.@DisplayName
: Provides a custom name for the test class or test method.@Disabled
: Disables the test method or class.
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. Assertions are used to check if a condition is true. If the condition is false, the test fails. Common assertions include:
assertEquals(expected, actual)
: Checks if two values are equal.assertTrue(condition)
: Checks if a condition is true.assertFalse(condition)
: Checks if a condition is false.assertNotNull(object)
: Checks if an object is not null.
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
JUnit 5 introduces the concept of dynamic tests, which can be generated at runtime. These are created using the DynamicTest
class.
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");
}
}
Running JUnit 5 Tests
JUnit 5 tests can be run in so many ways:
- IDE Integration: Most modern IDEs like IntelliJ IDEA, Eclipse, and NetBeans have built-in support for running JUnit 5 tests.
- Build Tools: You can use build tools like Maven and Gradle to run JUnit 5 tests. Ensure you have the necessary dependencies configured in your
pom.xml
or build.gradle
files. - Console Launcher: The JUnit Platform Console Launcher can be used to run tests from the command line.
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.
Similar Reads
What is Advanced Java?
In the realm of coding, creativity, and state-of-the-art technology have a pivotal role in the domain of software creation. Java is known for its platform independence, robustness, and extensive libraries. Advanced Java concepts let you make really complicated programs, it encompasses an array of te
13 min read
Dependency Injection(DI) Design Pattern
Effective dependency management is essential to building scalable and maintainable systems. The Dependency Injection (DI) design pattern is one strategy that has become very popular. Fundamentally, dependency injection is a method that addresses how components or objects are constructed and how they
10 min read
Spring
Introduction to Spring Framework
The Spring Framework is a powerful, lightweight, and widely used Java framework for building enterprise applications. It provides a comprehensive programming and configuration model for Java-based applications, making development faster, scalable, and maintainable.Before Enterprise Java Beans (EJB),
9 min read
Spring Framework Architecture
The Spring framework is a widely used open-source Java framework that provides a comprehensive programming and configuration model for building enterprise applications. Its architecture is designed around two core principles: Dependency Injection (DI) Aspect-Oriented Programming (AOP)The Spring fram
7 min read
Spring Initializr
Spring Initializr is a popular tool for quickly generating Spring Boot projects with essential dependencies. It helps developers set up a new application with minimal effort, supporting Maven and Gradle builds. With its user-friendly interface, it simplifies project configuration, making it an essen
4 min read
Spring - BeanFactory
The first and foremost thing when we talk about Spring is dependency injection which is possible because Spring is a container and behaves as a factory of Beans. Just like the BeanFactory interface is the simplest container providing an advanced configuration mechanism to instantiate, configure, and
4 min read
Spring - ApplicationContext
ApplicationContext belongs to the Spring framework. Spring IoC container is responsible for instantiating, wiring, configuring, and managing the entire life cycle of beans or objects. BeanFactory and ApplicationContext represent the Spring IoC Containers. ApplicationContext is the sub-interface of B
5 min read
Spring Dependency Injection with Example
Dependency Injection is the main functionality provided by Spring IOC(Inversion of Control). The Spring-Core module is responsible for injecting dependencies through either Constructor or Setter methods. The design principle of Inversion of Control emphasizes keeping the Java classes independent of
7 min read
Spring - IoC Container
The Spring framework is a powerful framework for building Java applications. It can be considered a collection of sub-frameworks, also referred to as layers, such as Spring AOP, Spring ORM, Spring Web Flow, and Spring Web MVC. We can use any of these modules separately while constructing a Web appli
2 min read
Spring - Autowiring
Autowiring in the Spring framework can inject dependencies automatically. The Spring container detects those dependencies specified in the configuration file and the relationship between the beans. This is referred to as Autowiring in Spring. To enable Autowiring in the Spring application we should
4 min read
Spring Framework Annotations
Spring framework is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. Spring framework mainly focuses on providing various ways to help you manage your business obje
6 min read
SpringBoot
Introduction to Spring Boot
Spring is widely used for creating scalable applications. For web applications, Spring provides Spring MVC, a commonly used module for building robust web applications. The major drawback of traditional Spring projects is that configuration can be time-consuming and overwhelming for new developers.
5 min read
Difference between Spring and Spring Boot
Spring Spring is an open-source lightweight framework that allows Java developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier
4 min read
Spring Boot - Architecture
Spring Boot is built on top of the core Spring framework. It simplifies and automates Spring-based application development by reducing the need for manual configuration. Spring Boot follows a layered architecture, where each layer interacts with other layers in a hierarchical order. The official Spr
3 min read
Spring Boot - Annotations
Spring Boot Annotations are a form of metadata that provides data about a spring application. Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the
7 min read
Spring Boot Actuator
Developing and managing an application are the two most important aspects of the applicationâs life cycle. It is very important to know what is going on beneath the application. Also, when we push the application into production, managing it gradually becomes critically important. Therefore, it is a
5 min read
Spring Boot - Code Structure
There is no specific layout or code structure for Spring Boot Projects. However, there are some best practices followed by developers that will help us too. You can divide your project into layers like service layer, entity layer, repository layer,, etc. You can also divide the project into modules.
3 min read
Spring - RestTemplate
Due to high traffic and quick access to services, REST APIs are getting more popular and have become the backbone of modern web development. It provides quick access to services and also provides fast data exchange between applications. REST is not a protocol or a standard, rather, it is a set of ar
7 min read
How to Change the Default Port in Spring Boot?
Spring Boot framework provides a default embedded server i.e. the Tomcat server for many configuration properties to run the Spring Boot application. The application runs on the default port which is 8080. As per the application need, we can also change this default port for the embedded server. In
4 min read
Spring Boot - Scheduling
Spring Boot provides the ability to schedule tasks for execution at a given time period with the help of @Scheduled annotation. This article provides a step by step guideline on how we can schedule tasks to run in a spring boot application Implementation:It is depicted below stepwise as follows:Â St
4 min read
Spring Boot - Sending Email via SMTP
Spring Boot provides the ability to send emails via SMTP using the JavaMail Library. Here we will be illustrating step-by-step guidelines to develop Restful web services that can be used to send emails with or without attachments. In order to begin with the steps, let us first create a Spring Boot p
5 min read
Spring Boot - REST Example
In modern web development, most applications follow the Client-Server Architecture. The Client (frontend) interacts with the server (backend) to fetch or save data. This communication happens using the HTTP protocol. On the server, we expose a bunch of services that are accessible via the HTTP proto
4 min read
Introduction to the Spring Data Framework
Spring Data is a powerful data access framework in the Spring ecosystem that simplifies database interactions for relational (SQL) and non-relational (NoSQL) databases. It eliminates boilerplate code and provides an easy-to-use abstraction layer for developers working with JPA, MongoDB, Redis, Cassa
3 min read
Spring MVC
Spring - MVC Framework
The Spring MVC Framework follows the Model-View-Controller architectural design pattern, which works around the Front Controller, i.e., the Dispatcher Servlet. The Dispatcher Servlet handles and dispatches all incoming HTTP requests to the appropriate controller. It uses @Controller and @RequestMapp
4 min read
Spring - Multi Action Controller with Example
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made
4 min read
Spring MVC using Java Based Configuration
Spring MVC framework enables the separation of modules, namely Model, View, and Controller, and seamlessly handles application integration. This enables the developer to create complex applications using plain Java classes. The model object can be passed between the view and the controller using map
3 min read
ViewResolver in Spring MVC
Spring MVC is a powerful Web MVC Framework for building web applications. It provides a structured way to develop web applications by separating concerns into Model, View, and Controller. One of the key features of Spring MVC is the ViewResolver, which enables you to render models in the browser wit
7 min read
Spring MVC - Exception Handling
Prerequisites: Spring MVC When something goes wrong with your application, the server displays an exception page defining the type of exception, the server-generated exception page is not user-friendly. Spring MVC provides exception handling for your web application to make sure you are sending your
6 min read
Spring - MVC Form Handling
Prerequisites: Spring MVC, Introduction to Spring Spring MVC is a Model-View-Controller framework, it enables the separation of modules into Model, View, and Controller and uniformly handles the application integration. In this article, we will create a student login form and see how Spring MVC hand
6 min read
How to Make Post Request in Java Spring?
Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JAVA is that Java tries to connect every conc
4 min read
Spring MVC CRUD with Example
In this article, we will explore how to build a Spring MVC CRUD application from scratch. CRUD stands for Create, Read/Retrieve, Update, and Delete. These are the four basic operations to create any type of project. Spring MVC is a popular framework for building web applications. Spring MVC follows
7 min read
What are Microservices?
Microservices are an architectural approach to developing software applications as a collection of small, independent services that communicate with each other over a network. Instead of building a monolithic application where all the functionality is tightly integrated into a single codebase, micro
12 min read