This tutorial will cover how to run Unit tests using the Maven’s Surefire plugin. If you are not familiar with Unit Testing, you can follow this tutorial for a quick catch-up.
In our Maven Project, we need the following mandatory dependencies:
<dependencies> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.4.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.4.2</version> <scope>test</scope> </dependency> </dependencies>
The junit-jupiter-engine dependency contains the implementation of the JUnit Jupiter test engine that runs our unit tests.
The junit-jupiter-api dependency provides API that allows us to write tests and extensions which use JUnit 5.
So Let’s create a very simple Java file:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class Example1 {
public static int getNumber() {
return 5;
}
public static String getMeaningfulText() {
return "Hello World";
}
}
Now let’s create a Test class for it:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestExample1 {
@Test
public void testNumber() {
assertEquals(5, Example1.getNumber());
}
@Test
public void testMeaningfulText () {
assertEquals(“Hello World”, Exampe1.getMeaningfulText ());
}
}
Finally, we can run our program by using mvn clean build and we should see Superfire plugin running our unit tests
[INFO] [INFO] --- maven-surefire-plugin:2.22.1:test (default-test) @ running-unit-tests --- [INFO]------------------------------------------------------- T E S T S-------------------------------------------------------Running net.javatutorial.junit5.JUnit5Example1Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.039 sec -in net.javatutorial.junit5.JUnit5Example1Results :Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 [INFO] ------------------------------------------------------------------------[ INFO] BUILD SUCCESS[ INFO] ------------------------------------------------------------------------