JUnit with Maven
T
/**
* JUNIT WITH MAVEN - BASIC TEST
* -----------------------------
* This example demonstrates how Maven integrates with JUnit
* to run automated tests.
*
* KEY CONCEPT:
* ------------
* - JUnit is a testing framework
* - Maven runs tests automatically during the build lifecycle
* - Tests are located in: src/test/java
*
* MAVEN COMMANDS:
* ---------------
* mvn test
* - Compiles main code and test code
* - Executes all test classes
* - Fails the build if any test fails
*
* mvn package
* - Run tests FIRST
* - Then package the application
* - Build fails if tests fails
*
* TEST DISCOVERY RULE:
* --------------------
* Maven automatically runs test classes named:
* *Test.java
* Test*.java
* *TestCase.java
*/
package demo;
import org.junit.Test;
import static org.junit.Assert.*;
public class TestJunitApp {
@Test
public void testSum() {
// ARANGE
int a = 5;
int b = 10;
// ACT
int result = a + b;
// ASSERT
assertEquals(15, result);
}
}
Pom
<?xml version="1.0" encoding="UTF-8"?>
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>demo</groupId>
<artifactId>testJuniApp</artifactId>
<packaging>jar</packaging>
<version>0.1.0</version>
<!-- Java version used by the compiler -->
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- JUnit 4 dependency (used only for tests) -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.5.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<transformers>
<transformer implementation=
"org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>demo.TestJuniApp</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>