Maven & Gradle Exercises
The first three exercises are pieces of logic that Maven and Gradle run on every build, written as pure functions with the tests already in place. Run the starter first: it prints placeholder answers, which shows what the tests expect. Complete the code marked TODO until the output matches the expected output, then compare with the solution. The last two exercises are real sessions to fix.
Exercise 1: Nearest-wins mediation
Topics: Version Mediation, dependencyManagement & BOMs
Walk the graph breadth-first from app's dependencies (in declaration order). The first version seen for a name wins; later ones are ignored. A managed version (from dependencyManagement) replaces whatever version is requested for that name, wherever it appears. Each node's dependencies are found under name@version.
GRAPH = {
"app": [("web", "1.0"), ("data", "1.0"), ("json", "2.1")],
"web@1.0": [("json", "2.5"), ("log", "1.2")],
"data@1.0": [("log", "1.4"), ("pool", "3.0")],
"pool@3.0": [("log", "2.0")],
"json@2.1": [], "json@2.5": [], "log@1.2": [], "log@1.4": [], "log@2.0": [],
}
def mediate(graph, managed=None):
# TODO: breadth-first walk, first version wins, managed versions override
return {}
print(mediate(GRAPH))
print(mediate(GRAPH, managed={"log": "2.0"})){}
{}
Expected output:
{'web': '1.0', 'data': '1.0', 'json': '2.1', 'log': '1.2', 'pool': '3.0'}
{'web': '1.0', 'data': '1.0', 'json': '2.1', 'log': '2.0', 'pool': '3.0'}Show solution
def mediate(graph, managed=None):
managed = managed or {}
chosen = {}
queue = list(graph["app"])
while queue:
name, version = queue.pop(0)
if name in chosen:
continue
version = managed.get(name, version)
chosen[name] = version
queue += graph[f"{name}@{version}"]
return chosenjson 2.1 is a direct dependency, so it beats web's 2.5. log 1.2 (depth 2, declared under web, which comes first) beats 1.4 (depth 2, under data) and 2.0 (depth 3). Managing log at 2.0 changes every occurrence.
Exercise 2: Maven version ranges
Topics: Enforcer Rules
Implement in_range(version, spec) for range specs such as [1.0,2.0): [/] include a bound, (/) exclude it, and an empty side is unbounded. Versions are dot-separated integers compared numerically (3.9.16 > 3.9).
def in_range(version, spec):
# TODO: parse the brackets and bounds, compare numerically
return None
for v, spec in [("1.5", "[1.0,2.0)"), ("2.0", "[1.0,2.0)"), ("2.0", "[1.0,2.0]"), ("1.0", "(1.0,)"),
("21", "[21,)"), ("3.9.16", "[3.9,4)"), ("0.9", "(,1.0]")]:
print(f"{v:7} in {spec:10} -> {in_range(v, spec)}")1.5 in [1.0,2.0) -> None
2.0 in [1.0,2.0) -> None
2.0 in [1.0,2.0] -> None
1.0 in (1.0,) -> None
21 in [21,) -> None
3.9.16 in [3.9,4) -> None
0.9 in (,1.0] -> None
Expected output:
1.5 in [1.0,2.0) -> True
2.0 in [1.0,2.0) -> False
2.0 in [1.0,2.0] -> True
1.0 in (1.0,) -> False
21 in [21,) -> True
3.9.16 in [3.9,4) -> True
0.9 in (,1.0] -> TrueShow solution
def vkey(v):
return tuple(int(x) for x in v.split("."))
def in_range(version, spec):
lo_inc, hi_inc = spec[0] == "[", spec[-1] == "]"
lo, hi = spec[1:-1].split(",")
v = vkey(version)
if lo and (v < vkey(lo) or (v == vkey(lo) and not lo_inc)):
return False
if hi and (v > vkey(hi) or (v == vkey(hi) and not hi_inc)):
return False
return TruePython compares tuples element by element, and a shorter tuple that is a prefix sorts first, so (3, 9) < (3, 9, 16) as Maven expects. (Maven's real comparison also understands qualifiers such as -alpha-1 or -SNAPSHOT.)
Exercise 3: Gradle's execution plan
Topics: The Task Graph
Return the execution order for the requested tasks: each task after all of its dependencies, each task once, requested tasks in the order given, and excluded tasks (-x) left out, together with anything that only they needed.
TASKS = {
"compileJava": [], "processResources": [], "classes": ["compileJava", "processResources"],
"jar": ["classes"], "compileTestJava": ["classes"], "testClasses": ["compileTestJava"],
"test": ["testClasses"], "assemble": ["jar"], "check": ["test"], "build": ["assemble", "check"],
}
def order(tasks, requested, excluded=()):
# TODO: depth-first, dependencies first, skip excluded tasks
return []
print(order(TASKS, ["jar"]))
print(order(TASKS, ["build"], excluded=("test",)))
print(order(TASKS, ["test", "jar"]))[]
[]
[]
Expected output:
['compileJava', 'processResources', 'classes', 'jar']
['compileJava', 'processResources', 'classes', 'jar', 'assemble', 'check', 'build']
['compileJava', 'processResources', 'classes', 'compileTestJava', 'testClasses', 'test', 'jar']Show solution
def order(tasks, requested, excluded=()):
result, seen = [], set()
def visit(t):
if t in seen or t in excluded:
return
seen.add(t)
for d in tasks[t]:
visit(d)
result.append(t)
for t in requested:
visit(t)
return resultExcluding test also drops testClasses and compileTestJava, because only test led to them; that matches the gradle build -x test -m session in the lesson.
Exercise 4: Fix the Gradle tests
Topics: Tests & JaCoCo Coverage, Version Catalogs
This build has a JUnit 5 test, but gradle test fails, and after the first obvious fix it fails differently. Read both messages, then make gradle test pass with the test really executed (build/test-results/test/TEST-demo.CalcTest.xml must exist). Hint: there are two problems, and both are in build.gradle.kts.
mkdir -p t/src/main/java/demo t/src/test/java/demo && cd t
echo 'rootProject.name = "t"' > settings.gradle.kts
cat > build.gradle.kts <<'KTS'
plugins { java }
repositories { mavenCentral() }
dependencies {
testImplementation("org.junit.jupiter:junit-jupiter:5.14.4")
}
KTS
echo 'package demo; public class Calc { public static int half(int x) { return x / 2; } }' > src/main/java/demo/Calc.java
cat > src/test/java/demo/CalcTest.java <<'SRC'
package demo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class CalcTest { @Test void halves() { assertEquals(3, Calc.half(7)); } }
SRC
echo "--- as given"
gradle test 2>&1 | grep -o 'There are test sources.*to execute.'
echo 'tasks.test { useJUnitPlatform() }' >> build.gradle.kts
echo "--- with useJUnitPlatform()"
gradle test 2>&1 | grep -o 'Failed to load JUnit Platform.'--- as given
There are test sources present and no filters are applied, but the test task did not discover any tests to execute.
--- with useJUnitPlatform()
Failed to load JUnit Platform.
Show solution
The test task needs both useJUnitPlatform() and the JUnit Platform launcher on the test runtime classpath (required since Gradle 9). Align the launcher's version with the BOM:
dependencies {
testImplementation(platform("org.junit:junit-bom:5.14.4"))
testImplementation("org.junit.jupiter:junit-jupiter")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
tasks.test { useJUnitPlatform() }Now the test runs and passes (7 / 2 is 3 in integer division), and ls build/test-results/test shows TEST-demo.CalcTest.xml. The version-less junit-platform-launcher gets its version (1.14.4) from the BOM, which keeps Platform and Jupiter aligned.
Exercise 5: Make the Maven build converge
Topics: Version Mediation, Enforcer Rules
Recreate the alpha/beta/gamma/text-util libraries from the mediation lesson, add the enforcer with dependencyConvergence to the app, and make mvn verify pass and the program print GAMMA! without changing any library. Then explain in one sentence why an <exclusion> of text-util under alpha would also satisfy the rule.
Show solution
Pin the version in the app's POM:
<dependencyManagement>
<dependencies>
<dependency><groupId>org.acme</groupId><artifactId>text-util</artifactId><version>2.0</version></dependency>
</dependencies>
</dependencyManagement>dependencyConvergence checks the tree after dependencyManagement is applied, so every path now leads to 2.0. With an exclusion, alpha's path to text-util disappears from the tree, leaving 2.0 as the only version; it converges too, but it hides alpha's declared requirement, so prefer the managed version.
Test yourself
In Exercise 1, why does json resolve to 2.1 although web asks for 2.5?
- 2.1 is newer
- 2.1 is declared directly by app, so it is nearest
- json is managed
- Alphabetical order
Which two things does a Gradle 9 build need to run JUnit 5 tests?
- jacoco and the wrapper
useJUnitPlatform()on the test task and the JUnit Platform launcher on the test runtime classpath- A version catalog and buildSrc
- Maven's surefire plugin