![]() |
JUnit 5 is a widely used testing framework in the Java ecosystem. It is the successor of JUnit 4 and is designed to address its limitations. JUnit framework allows the developers to write and run the tests for their Java code. These tests help ensure that the code functions correctly and continues to work as expected as changes are made. Using Maven Dependency in JUnit 5Maven is a popular build management tool in the Spring Boot framework. Instead of the Gradle build management tool, the Maven dependency management tool allows us to configure the pom.xml file. Prerequisites to the TopicTo understand this, we need to have some prerequisites. They are:
Required Maven Dependencies for JUnit 5
IDE Setup JUnit 5 Maven DependencyHere, we use Eclipse IDE for Java and Web Developers 2023-06. You may also use other platforms like IntelliJ, Spring suite tool, Spring Initializer, etc. Step By Step Implementation of the ApplicationStep 1: Creation of Project
Recommended requirements:Project type: Maven (Mandatory)
Step 2: Adding dependenciesLet us configure our `pom.xml` file with the following dependencies: JUnit Jupiter API
XML
Project Setup for the ApplicationNow, the project setup is ready, let us look into an example to understand how to write and run the test cases of JUnit using the Maven tool. Step 1: Create a new package in the `src/test/java`, right-click on `src/test/java` > new > package. After Creating Package:Step 2: Create a class inside the package and name the class. i.e. `Addition`. To create a class, right-click on package > new > class After Creating Class:Step 3: Write the logic which you want to test in `Addition.java`. Java
Step 4: Now, create a test case inside the package by right click on the package > new > others > java > JUnit > JUnit test case.
Example of Testcase1:Test Script: Let us write the first test case i.e. `Testcase1`. Java
Explanation of the Program:The above code snippet is the basic script of a test case. In the class `Testcase1`, we defined a method named `test1` which is annotated with `@Test` representing it is a test method. We have created an `addition` object for `Addition.java` and calculated the sum of two numbers and stored it in `actual` variable and asserting it with `expected` value using `assertEquals()` method. Steps to run the ApplicationTo run the application, go to project explorer > right-click on your project > Run as > Spring Boot App. Output of ApplicationJUnit View:Console View: |
Reffered: https://www.geeksforgeeks.org
Advance Java |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |