What is the usage of JUnit in Maven?
The steps for using JUnit in a Maven project are as follows:
- Add the JUnit dependency in the pom.xml file.
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
- Create a JUnit test class following the naming convention of ending in “Test”, such as MyClassTest.java.
- In the test class, label the test method with the @Test annotation.
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class MyClassTest {
@Test
public void testAddition() {
MyClass obj = new MyClass();
int result = obj.add(2, 3);
assertEquals(5, result);
}
}
- Run tests using Maven command.
mvn test
Maven will automatically run all the methods in the test class that are annotated with @Test, and display the test results.
Note: When using JUnit, the test class and test methods must be declared with the public access modifier.