Sub topic 3
Running Tests with JUnit 5 in Maven and Gradle
Running Tests
A unit test is a small piece of code that checks one piece of your program. JUnit 5 is the most common test library for Java. Put tests in src/test/java, and the build tool will find them.
package com.example;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class AppTest {
@Test
void greetsByName() {
assertEquals("Hello, Maven!", App.greeting("Maven"));
}
}In Maven, the Surefire plugin runs tests during the test phase. In Gradle, the test task runs them once you call useJUnitPlatform().
mvn test
./gradlew testReproducible Builds with Wrappers
A wrapper is a small script that downloads one fixed version of the build tool. Every developer and every CI server then builds the same way.
mvn wrapper:wrapper
./mvnw clean verify
gradle wrapper
./gradlew buildCommit the wrapper files to version control.
Transitive Dependencies
A transitive dependency is a library that one of your own dependencies needs. Sometimes two libraries ask for different versions of the same library. That is a version conflict. To see every library and which version won, print the dependency tree:
mvn dependency:tree
./gradlew dependencies --configuration runtimeClasspathIf you don't want a transitive library at all, Maven lets you remove it with an <exclusion> inside the dependency that brings it in.
Plugins
A plugin adds new work to a build, such as compiling, testing, or packaging. In Maven you list plugins under <build><plugins>. In Gradle you apply them in the plugins { } block, for example application.
Multi-Module Builds
Large projects split into parts called modules. In Maven, a parent POM with pom packaging lists the modules. In Gradle, settings.gradle.kts uses include("core", "app"), and app depends on core through implementation(project(":core")).
Incremental Builds and Caching
Gradle checks whether a task's inputs and outputs have changed. If nothing changed, it skips the task and marks it UP-TO-DATE. The build cache goes a step further. It can reuse a task's outputs from an earlier build, even one that ran on another machine.
Maven or Gradle?
| Question | Maven | Gradle |
|---|---|---|
| Build file | XML (`pom.xml`) | Kotlin code (`build.gradle.kts`) |
| Style | Fixed lifecycle, strong conventions | Flexible task graph |
| Speed on big projects | Good | Often faster, thanks to caching |
| Best for | Simple, standard projects | Large or custom builds |
Exercise
Your teammate gets a different build result than you do because they installed a newer Gradle. What should the project use to fix this?
Show answer
The Gradle Wrapper. Run gradle wrapper once, commit the files, and have everyone build with ./gradlew so all machines use the same Gradle version.
Exercise
Which command shows why an unexpected library version ends up in a Maven build?
Show answer
mvn dependency:tree, which prints every direct and transitive dependency and the version Maven chose.