Build Tools, Modules & JUnit – Java
Maven/Gradle, dependencies, JAR files and testing with JUnit 5.
Real projects use a build tool: Maven (pom.xml, XML) or Gradle (build.gradle, Groovy or Kotlin DSL). They download dependencies from Maven Central, compile, test and build a JAR. The folder structure is standardized: src/main/java for code, src/test/java for tests.
# Maven
mvn clean package # compile, test, build JAR
mvn test # tests only
java -jar target/app.jar
# Gradle
./gradlew build
./gradlew test
./gradlew runA minimal Gradle build script (Groovy DSL) for a project with JUnit 5:
plugins {
id 'java'
id 'application'
}
repositories { mavenCentral() }
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter:5.10.2'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}
application { mainClass = 'Main' }
java { toolchain { languageVersion = JavaLanguageVersion.of(21) } }
test { useJUnitPlatform() }You write tests with JUnit 5. Every method with @Test is a test case; assertions check expectations:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class Rechner {
static int add(int a, int b) { return a + b; }
static int teile(int a, int b) { return a / b; }
}
class RechnerTest {
@Test
void addiertZahlen() {
assertEquals(5, Rechner.add(2, 3));
}
@Test
void teilenDurchNullWirftFehler() {
assertThrows(ArithmeticException.class, () -> Rechner.teile(1, 0));
}
}Since Java 9 there is the module system (module-info.java), with which you define which packages a module exports and which modules it requires. In everyday work the classpath is usually enough for applications; modules are mainly interesting for libraries and jlink (slim runtime images).
module com.beispiel.app {
requires java.net.http;
exports com.beispiel.app.api;
}@ParameterizedTest for many similar inputs. Frameworks such as Spring Boot are built on these tools.