New posts
This commit is contained in:
@@ -0,0 +1,39 @@
|
|||||||
|
# extendwith
|
||||||
|
|
||||||
|
Companion code for [JUnit @ExtendWith Explained (JUnit 5 and 6): Write Your First Extension](https://ankurm.com/mastering-junit-5-extendwith-the-ultimate-guide-to-the-jupiter-extension-model/) on ankurm.com. Deeper extension material: [JUnit 6 extensions](https://ankurm.com/junit-6-extensions/), [advanced extensions](https://ankurm.com/advanced-extensions-junit-6/).
|
||||||
|
|
||||||
|
Three small extensions (a timing extension, a `ParameterResolver`, a `TestExecutionExceptionHandler`) and fixtures that show where `@ExtendWith` can go, in which order extensions run, and how `@RegisterExtension` and ServiceLoader registration differ. Every transcript quoted in the article is in [`output/`](output).
|
||||||
|
|
||||||
|
## Versions
|
||||||
|
|
||||||
|
| Component | Version |
|
||||||
|
|---|---|
|
||||||
|
| JUnit Jupiter (default) | 6.1.3 (GA 2026-08-07) |
|
||||||
|
| JUnit Jupiter (`-Pjunit5`) | 5.14.4, Platform 1.14.4 |
|
||||||
|
| Mockito (`mockito-junit-jupiter`) | 5.24.0 |
|
||||||
|
| JDK | 25 (`maven.compiler.release` 25); the extensions also compile with `--release 17` |
|
||||||
|
|
||||||
|
## Run
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mvn test # JUnit 6.1.3 -> output/01..08, 13
|
||||||
|
mvn -Pjunit5 test # JUnit 5.14.4 -> output/junit5/ (same sources, identical transcripts)
|
||||||
|
scripts/run-all.sh # both, plus the javap/javac probes -> output/09..12
|
||||||
|
```
|
||||||
|
|
||||||
|
Needs JDK 17+ and Maven; `scripts/versions.sh` downloads a few jars from Maven Central.
|
||||||
|
|
||||||
|
## Files
|
||||||
|
|
||||||
|
| Path | What |
|
||||||
|
|---|---|
|
||||||
|
| `src/test/java/.../ext/` | The extensions: `TimingExtension`, `ApiKeyResolver`, `NetworkTimeoutHandler`, `LifecycleExtension`, `First/SecondExtension`, `TimedTest` (composed annotation), and the earlier post's `PerformanceTrackerExtension`, `TransactionalExtension`, `TempDirectoryExtension` |
|
||||||
|
| `src/test/java/.../fixtures/` | Test classes that the Platform runs on demand (excluded from Surefire) |
|
||||||
|
| `ExtendWithTest.java`, `Runner.java` | Start the Platform on one fixture at a time, write `output/NN-*.txt`, assert the same facts |
|
||||||
|
| `src/test/resources/META-INF/services/` | ServiceLoader registration of `AutoRegisteredExtension` |
|
||||||
|
| `src/spring/UserProfileServiceTest.java` | The earlier post's Spring snippet: compiled by `scripts/versions.sh`, not executed |
|
||||||
|
| `output/01-levels.txt` ... `13-lifecycle-order.txt` | Captured evidence, see the article for which block each one backs |
|
||||||
|
|
||||||
|
## Honest limits
|
||||||
|
|
||||||
|
Millisecond figures are masked as `N` in the transcripts (the tests assert lower bounds instead). `TempDirectoryExtension` only logs; it creates no directory. Output 12 proves the Spring snippet compiles, nothing more.
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
LevelsFixture (@ExtendWith(FirstExtension) on the class; SecondExtension on one method)
|
||||||
|
FirstExtension created
|
||||||
|
FirstExtension.beforeAll LevelsFixture
|
||||||
|
FirstExtension.beforeEach classLevelOnly()
|
||||||
|
test classLevelOnly
|
||||||
|
FirstExtension.afterEach classLevelOnly()
|
||||||
|
SecondExtension created
|
||||||
|
FirstExtension.beforeEach methodLevelToo()
|
||||||
|
SecondExtension.beforeEach methodLevelToo()
|
||||||
|
test methodLevelToo
|
||||||
|
SecondExtension.afterEach methodLevelToo()
|
||||||
|
FirstExtension.afterEach methodLevelToo()
|
||||||
|
FirstExtension.beforeAll Inner
|
||||||
|
FirstExtension.beforeEach insideNested()
|
||||||
|
test insideNested
|
||||||
|
FirstExtension.afterEach insideNested()
|
||||||
|
FirstExtension.afterAll Inner
|
||||||
|
FirstExtension.afterAll LevelsFixture
|
||||||
|
-- results
|
||||||
|
classLevelOnly() -> SUCCESSFUL
|
||||||
|
methodLevelToo() -> SUCCESSFUL
|
||||||
|
insideNested() -> SUCCESSFUL
|
||||||
|
|
||||||
|
ParameterLevelFixture (@ExtendWith(ApiKeyResolver) on the parameter itself)
|
||||||
|
ApiKeyResolver.resolveParameter parameter 0 -> key for 'billing'
|
||||||
|
test got sk-test-billing
|
||||||
|
-- results
|
||||||
|
keyFromParameterAnnotation(String) -> SUCCESSFUL
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
StackedFixture @ExtendWith(First) then @ExtendWith(Second)
|
||||||
|
FirstExtension created
|
||||||
|
SecondExtension created
|
||||||
|
FirstExtension.beforeAll StackedFixture
|
||||||
|
SecondExtension.beforeAll StackedFixture
|
||||||
|
FirstExtension.beforeEach test()
|
||||||
|
SecondExtension.beforeEach test()
|
||||||
|
test
|
||||||
|
SecondExtension.afterEach test()
|
||||||
|
FirstExtension.afterEach test()
|
||||||
|
SecondExtension.afterAll StackedFixture
|
||||||
|
FirstExtension.afterAll StackedFixture
|
||||||
|
-- results
|
||||||
|
test() -> SUCCESSFUL
|
||||||
|
|
||||||
|
ArrayFixture @ExtendWith({Second, First})
|
||||||
|
SecondExtension created
|
||||||
|
FirstExtension created
|
||||||
|
SecondExtension.beforeAll ArrayFixture
|
||||||
|
FirstExtension.beforeAll ArrayFixture
|
||||||
|
SecondExtension.beforeEach test()
|
||||||
|
FirstExtension.beforeEach test()
|
||||||
|
test
|
||||||
|
FirstExtension.afterEach test()
|
||||||
|
SecondExtension.afterEach test()
|
||||||
|
FirstExtension.afterAll ArrayFixture
|
||||||
|
SecondExtension.afterAll ArrayFixture
|
||||||
|
-- results
|
||||||
|
test() -> SUCCESSFUL
|
||||||
|
|
||||||
|
RegisterExtensionOrderFixture first=@Order(2), second=@Order(1)
|
||||||
|
FirstExtension created
|
||||||
|
SecondExtension created
|
||||||
|
SecondExtension.beforeAll RegisterExtensionOrderFixture
|
||||||
|
FirstExtension.beforeAll RegisterExtensionOrderFixture
|
||||||
|
SecondExtension.beforeEach test()
|
||||||
|
FirstExtension.beforeEach test()
|
||||||
|
test
|
||||||
|
FirstExtension.afterEach test()
|
||||||
|
SecondExtension.afterEach test()
|
||||||
|
FirstExtension.afterAll RegisterExtensionOrderFixture
|
||||||
|
SecondExtension.afterAll RegisterExtensionOrderFixture
|
||||||
|
-- results
|
||||||
|
test() -> SUCCESSFUL
|
||||||
|
|
||||||
|
MixedFixture @ExtendWith(Second) on the class, @RegisterExtension First field
|
||||||
|
SecondExtension created
|
||||||
|
FirstExtension created
|
||||||
|
SecondExtension.beforeAll MixedFixture
|
||||||
|
FirstExtension.beforeAll MixedFixture
|
||||||
|
SecondExtension.beforeEach test()
|
||||||
|
FirstExtension.beforeEach test()
|
||||||
|
test
|
||||||
|
FirstExtension.afterEach test()
|
||||||
|
SecondExtension.afterEach test()
|
||||||
|
FirstExtension.afterAll MixedFixture
|
||||||
|
SecondExtension.afterAll MixedFixture
|
||||||
|
-- results
|
||||||
|
test() -> SUCCESSFUL
|
||||||
|
|
||||||
|
DuplicateFixture @ExtendWith(First) on the class AND on the method
|
||||||
|
FirstExtension created
|
||||||
|
FirstExtension.beforeAll DuplicateFixture
|
||||||
|
FirstExtension.beforeEach test()
|
||||||
|
test
|
||||||
|
FirstExtension.afterEach test()
|
||||||
|
FirstExtension.afterAll DuplicateFixture
|
||||||
|
-- results
|
||||||
|
test() -> SUCCESSFUL
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
@ExtendWith (LevelsFixture, output 01): extension instances created
|
||||||
|
FirstExtension created
|
||||||
|
SecondExtension created
|
||||||
|
|
||||||
|
@RegisterExtension with a constructor argument (RegisterExtensionFixture)
|
||||||
|
>>> EXTENSION: Initializing directory at /custom/path/logs
|
||||||
|
Using directory: /custom/path/logs
|
||||||
|
>>> EXTENSION: Cleaning up directory at /custom/path/logs
|
||||||
|
-- results
|
||||||
|
testLogCreation() -> SUCCESSFUL
|
||||||
|
|
||||||
|
ServiceLoader, junit.jupiter.extensions.autodetection.enabled not set (PlainFixture)
|
||||||
|
test
|
||||||
|
-- results
|
||||||
|
test() -> SUCCESSFUL
|
||||||
|
|
||||||
|
ServiceLoader, junit.jupiter.extensions.autodetection.enabled=true (PlainFixture)
|
||||||
|
AutoRegisteredExtension.beforeEach test()
|
||||||
|
test
|
||||||
|
-- results
|
||||||
|
test() -> SUCCESSFUL
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
TimingFixture (@ExtendWith(TimingExtension.class))
|
||||||
|
TimingExtension.beforeEach fast()
|
||||||
|
test fast
|
||||||
|
TimingExtension.afterEach fast() took N ms
|
||||||
|
TimingExtension.beforeEach slow()
|
||||||
|
test slow (slept 30 ms)
|
||||||
|
TimingExtension.afterEach slow() took N ms
|
||||||
|
-- results
|
||||||
|
fast() -> SUCCESSFUL
|
||||||
|
slow() -> SUCCESSFUL
|
||||||
|
|
||||||
|
ComposedFixture (@TimedTest = @Test + @ExtendWith(TimingExtension))
|
||||||
|
TimingExtension.beforeEach timedWithOneAnnotation()
|
||||||
|
test timedWithOneAnnotation
|
||||||
|
TimingExtension.afterEach timedWithOneAnnotation() took N ms
|
||||||
|
-- results
|
||||||
|
timedWithOneAnnotation() -> SUCCESSFUL
|
||||||
|
|
||||||
|
(the millisecond figure is masked as N; the test asserts that slow() took at least 30 ms)
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
ResolverFixture (@ExtendWith(ApiKeyResolver.class) on the class)
|
||||||
|
ApiKeyResolver.resolveParameter parameter 0 -> key for 'default'
|
||||||
|
test got sk-test-default
|
||||||
|
ApiKeyResolver.resolveParameter parameter 0 -> key for 'payments'
|
||||||
|
test got sk-test-payments
|
||||||
|
-- results
|
||||||
|
unannotatedParameter(String) -> FAILED (ParameterResolutionException: No ParameterResolver registered for parameter [java.lang.String arg0] in method [void com.ankurm.tutorials.junit.extendwith.fixtures.ResolverFixture.unannotatedParameter(java.lang.String)].)
|
||||||
|
defaultKey(String) -> SUCCESSFUL
|
||||||
|
namedKey(String) -> SUCCESSFUL
|
||||||
|
|
||||||
|
CompetingResolversFixture (two resolvers both support the parameter)
|
||||||
|
-- results
|
||||||
|
ambiguous(String) -> FAILED (ParameterResolutionException: Discovered multiple competing ParameterResolvers for parameter [java.lang.String arg0] in method [void com.ankurm.tutorials.junit.extendwith.fixtures.CompetingResolversFixture.ambiguous(java.lang.String)]: com.ankurm.tutorials.junit.extendwith.ext.ApiKeyResolver@HASH, com.ankurm.tutorials.junit.extendwith.ext.OtherApiKeyResolver@HASH)
|
||||||
|
|
||||||
|
(object hash codes in the last message are masked as @HASH)
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
ExceptionHandlerFixture (@ExtendWith(NetworkTimeoutHandler.class))
|
||||||
|
test passes
|
||||||
|
NetworkTimeoutHandler swallowed NetworkTimeoutException in remoteServiceTimesOut()
|
||||||
|
NetworkTimeoutHandler rethrowing AssertionFailedError in assertionStillFails()
|
||||||
|
NetworkTimeoutHandler rethrowing IllegalStateException in realBug()
|
||||||
|
-- results
|
||||||
|
passes() -> SUCCESSFUL
|
||||||
|
remoteServiceTimesOut() -> ABORTED (TestAbortedException: remote service unavailable: no answer from payments after 2000 ms)
|
||||||
|
assertionStillFails() -> FAILED (AssertionFailedError: expected: <4> but was: <5>)
|
||||||
|
realBug() -> FAILED (IllegalStateException: total is negative)
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
@ExtendWith @Target = [FIELD, METHOD, PARAMETER, TYPE]
|
||||||
|
@ExtendWith @Repeatable = Extensions
|
||||||
|
@ExtendWith @Inherited = true
|
||||||
|
@Extensions @Target = [FIELD, METHOD, PARAMETER, TYPE]
|
||||||
|
@RegisterExtension @Target = [FIELD]
|
||||||
|
@ExtendWith value() type = Class[]
|
||||||
|
StackedFixture has two @ExtendWith; the compiler stored them as one @Extensions
|
||||||
|
ApiKeyResolver.class.getInterfaces() = [ParameterResolver]
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
OriginalExamplesFixture (PerformanceTrackerExtension, TransactionalExtension)
|
||||||
|
>>> PERFORMANCE: Test [myTest()] took N ms
|
||||||
|
>>> DB: Starting Transaction for testUserSave()
|
||||||
|
Executing: Saving User to DB
|
||||||
|
>>> DB: Rolling back Transaction for testUserSave()
|
||||||
|
-- results
|
||||||
|
myTest() -> SUCCESSFUL
|
||||||
|
testUserSave() -> SUCCESSFUL
|
||||||
|
|
||||||
|
RegisterExtensionFixture (TempDirectoryExtension)
|
||||||
|
>>> EXTENSION: Initializing directory at /custom/path/logs
|
||||||
|
Using directory: /custom/path/logs
|
||||||
|
>>> EXTENSION: Cleaning up directory at /custom/path/logs
|
||||||
|
-- results
|
||||||
|
testLogCreation() -> SUCCESSFUL
|
||||||
|
|
||||||
|
(the millisecond figure is masked as N; the fixture sleeps 42 ms and the test asserts at least 42)
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
== Class-file version of ExtendWith.class (major 52 = Java 8, 61 = Java 17)
|
||||||
|
junit-jupiter-api 5.14.4: major version: 52
|
||||||
|
junit-jupiter-api 6.1.3: major version: 61
|
||||||
|
|
||||||
|
== ExtensionContext.Store: getOrComputeIfAbsent and computeIfAbsent
|
||||||
|
-- junit-jupiter-api 5.14.4
|
||||||
|
public default <V> V getOrComputeIfAbsent(java.lang.Class<V>);
|
||||||
|
public abstract <K, V> java.lang.Object getOrComputeIfAbsent(K, java.util.function.Function<K, V>);
|
||||||
|
public abstract <K, V> V getOrComputeIfAbsent(K, java.util.function.Function<K, V>, java.lang.Class<V>);
|
||||||
|
-- junit-jupiter-api 6.1.3
|
||||||
|
public default <V> V getOrComputeIfAbsent(java.lang.Class<V>);
|
||||||
|
public default <V> V computeIfAbsent(java.lang.Class<V>);
|
||||||
|
public abstract <K, V> java.lang.Object getOrComputeIfAbsent(K, java.util.function.Function<? super K, ? extends V>);
|
||||||
|
public abstract <K, V> java.lang.Object computeIfAbsent(K, java.util.function.Function<? super K, ? extends V>);
|
||||||
|
public abstract <K, V> V getOrComputeIfAbsent(K, java.util.function.Function<? super K, ? extends V>, java.lang.Class<V>);
|
||||||
|
public abstract <K, V> V computeIfAbsent(K, java.util.function.Function<? super K, ? extends V>, java.lang.Class<V>);
|
||||||
|
|
||||||
|
== InvocationInterceptor.interceptDynamicTest
|
||||||
|
-- junit-jupiter-api 5.14.4
|
||||||
|
public default void interceptDynamicTest(InvocationInterceptor$Invocation<java.lang.Void>, ExtensionContext);
|
||||||
|
public default void interceptDynamicTest(InvocationInterceptor$Invocation<java.lang.Void>, DynamicTestInvocationContext, ExtensionContext);
|
||||||
|
-- junit-jupiter-api 6.1.3
|
||||||
|
public default void interceptDynamicTest(InvocationInterceptor$Invocation<java.lang.Void>, DynamicTestInvocationContext, ExtensionContext);
|
||||||
|
|
||||||
|
== A Store call compiled with -Xlint:deprecation (StoreProbe.java)
|
||||||
|
-- against JUnit 5.14.4
|
||||||
|
javac exit status: 0
|
||||||
|
-- against JUnit 6.1.3
|
||||||
|
StoreProbe.java:5: warning: [deprecation] <K,V>getOrComputeIfAbsent(K,Function<? super K,? extends V>) in Store has been deprecated
|
||||||
|
return store.getOrComputeIfAbsent("k", k -> "v");
|
||||||
|
^
|
||||||
|
where K,V are type-variables:
|
||||||
|
K extends Object declared in method <K,V>getOrComputeIfAbsent(K,Function<? super K,? extends V>)
|
||||||
|
V extends Object declared in method <K,V>getOrComputeIfAbsent(K,Function<? super K,? extends V>)
|
||||||
|
1 warning
|
||||||
|
javac exit status: 0
|
||||||
|
-- the 6.x replacement computeIfAbsent (ComputeProbe.java)
|
||||||
|
against JUnit 5.14.4: javac exit status 1
|
||||||
|
target/probe/src/ComputeProbe.java:5: error: cannot find symbol
|
||||||
|
return store.computeIfAbsent("k", k -> "v");
|
||||||
|
^
|
||||||
|
against JUnit 6.1.3: javac exit status 0
|
||||||
|
|
||||||
|
== The module's extensions (src/test/java/.../ext) compiled unchanged with --release 17
|
||||||
|
JUnit 5.14.4: 14 class files, javac exit status 0
|
||||||
|
JUnit 6.1.3: 14 class files, javac exit status 0
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
== Is the annotation itself an @ExtendWith? (javap -v, RuntimeVisibleAnnotations)
|
||||||
|
-- @MockitoSettings (mockito-junit-jupiter-5.24.0.jar)
|
||||||
|
Lorg/junit/jupiter/api/extension/ExtendWith;
|
||||||
|
Lorg/mockito/junit/jupiter/MockitoExtension;
|
||||||
|
-- @SpringJUnitConfig (spring-test-7.0.10.jar)
|
||||||
|
Lorg/junit/jupiter/api/extension/ExtendWith;
|
||||||
|
Lorg/springframework/test/context/junit/jupiter/SpringExtension;
|
||||||
|
-- @SpringBootTest (spring-boot-test-4.1.2.jar)
|
||||||
|
Lorg/junit/jupiter/api/extension/ExtendWith;
|
||||||
|
Lorg/springframework/test/context/junit/jupiter/SpringExtension;
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
diff -r output output/junit5 (files 01-08; JUnit 6.1.3 on the left, JUnit 5.14.4 on the right)
|
||||||
|
no differences: all 8 transcripts are byte-for-byte identical
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
== src/spring/UserProfileServiceTest.java compiled against spring-test 7.0.10, spring-boot-test 4.1.2, mockito-junit-jupiter 5.24.0, JUnit 6.1.3
|
||||||
|
javac exit status: 0
|
||||||
|
(compiled only: running it would need a Spring Boot application class and context)
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
LifecycleFixture (LifecycleExtension + the class's own @BeforeAll/@BeforeEach/@AfterEach/@AfterAll)
|
||||||
|
BeforeAllCallback
|
||||||
|
@BeforeAll
|
||||||
|
BeforeEachCallback
|
||||||
|
@BeforeEach
|
||||||
|
BeforeTestExecutionCallback
|
||||||
|
@Test
|
||||||
|
AfterTestExecutionCallback
|
||||||
|
@AfterEach
|
||||||
|
AfterEachCallback
|
||||||
|
@AfterAll
|
||||||
|
AfterAllCallback
|
||||||
|
-- results
|
||||||
|
test() -> SUCCESSFUL
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
LevelsFixture (@ExtendWith(FirstExtension) on the class; SecondExtension on one method)
|
||||||
|
FirstExtension created
|
||||||
|
FirstExtension.beforeAll LevelsFixture
|
||||||
|
FirstExtension.beforeEach classLevelOnly()
|
||||||
|
test classLevelOnly
|
||||||
|
FirstExtension.afterEach classLevelOnly()
|
||||||
|
SecondExtension created
|
||||||
|
FirstExtension.beforeEach methodLevelToo()
|
||||||
|
SecondExtension.beforeEach methodLevelToo()
|
||||||
|
test methodLevelToo
|
||||||
|
SecondExtension.afterEach methodLevelToo()
|
||||||
|
FirstExtension.afterEach methodLevelToo()
|
||||||
|
FirstExtension.beforeAll Inner
|
||||||
|
FirstExtension.beforeEach insideNested()
|
||||||
|
test insideNested
|
||||||
|
FirstExtension.afterEach insideNested()
|
||||||
|
FirstExtension.afterAll Inner
|
||||||
|
FirstExtension.afterAll LevelsFixture
|
||||||
|
-- results
|
||||||
|
classLevelOnly() -> SUCCESSFUL
|
||||||
|
methodLevelToo() -> SUCCESSFUL
|
||||||
|
insideNested() -> SUCCESSFUL
|
||||||
|
|
||||||
|
ParameterLevelFixture (@ExtendWith(ApiKeyResolver) on the parameter itself)
|
||||||
|
ApiKeyResolver.resolveParameter parameter 0 -> key for 'billing'
|
||||||
|
test got sk-test-billing
|
||||||
|
-- results
|
||||||
|
keyFromParameterAnnotation(String) -> SUCCESSFUL
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
StackedFixture @ExtendWith(First) then @ExtendWith(Second)
|
||||||
|
FirstExtension created
|
||||||
|
SecondExtension created
|
||||||
|
FirstExtension.beforeAll StackedFixture
|
||||||
|
SecondExtension.beforeAll StackedFixture
|
||||||
|
FirstExtension.beforeEach test()
|
||||||
|
SecondExtension.beforeEach test()
|
||||||
|
test
|
||||||
|
SecondExtension.afterEach test()
|
||||||
|
FirstExtension.afterEach test()
|
||||||
|
SecondExtension.afterAll StackedFixture
|
||||||
|
FirstExtension.afterAll StackedFixture
|
||||||
|
-- results
|
||||||
|
test() -> SUCCESSFUL
|
||||||
|
|
||||||
|
ArrayFixture @ExtendWith({Second, First})
|
||||||
|
SecondExtension created
|
||||||
|
FirstExtension created
|
||||||
|
SecondExtension.beforeAll ArrayFixture
|
||||||
|
FirstExtension.beforeAll ArrayFixture
|
||||||
|
SecondExtension.beforeEach test()
|
||||||
|
FirstExtension.beforeEach test()
|
||||||
|
test
|
||||||
|
FirstExtension.afterEach test()
|
||||||
|
SecondExtension.afterEach test()
|
||||||
|
FirstExtension.afterAll ArrayFixture
|
||||||
|
SecondExtension.afterAll ArrayFixture
|
||||||
|
-- results
|
||||||
|
test() -> SUCCESSFUL
|
||||||
|
|
||||||
|
RegisterExtensionOrderFixture first=@Order(2), second=@Order(1)
|
||||||
|
FirstExtension created
|
||||||
|
SecondExtension created
|
||||||
|
SecondExtension.beforeAll RegisterExtensionOrderFixture
|
||||||
|
FirstExtension.beforeAll RegisterExtensionOrderFixture
|
||||||
|
SecondExtension.beforeEach test()
|
||||||
|
FirstExtension.beforeEach test()
|
||||||
|
test
|
||||||
|
FirstExtension.afterEach test()
|
||||||
|
SecondExtension.afterEach test()
|
||||||
|
FirstExtension.afterAll RegisterExtensionOrderFixture
|
||||||
|
SecondExtension.afterAll RegisterExtensionOrderFixture
|
||||||
|
-- results
|
||||||
|
test() -> SUCCESSFUL
|
||||||
|
|
||||||
|
MixedFixture @ExtendWith(Second) on the class, @RegisterExtension First field
|
||||||
|
SecondExtension created
|
||||||
|
FirstExtension created
|
||||||
|
SecondExtension.beforeAll MixedFixture
|
||||||
|
FirstExtension.beforeAll MixedFixture
|
||||||
|
SecondExtension.beforeEach test()
|
||||||
|
FirstExtension.beforeEach test()
|
||||||
|
test
|
||||||
|
FirstExtension.afterEach test()
|
||||||
|
SecondExtension.afterEach test()
|
||||||
|
FirstExtension.afterAll MixedFixture
|
||||||
|
SecondExtension.afterAll MixedFixture
|
||||||
|
-- results
|
||||||
|
test() -> SUCCESSFUL
|
||||||
|
|
||||||
|
DuplicateFixture @ExtendWith(First) on the class AND on the method
|
||||||
|
FirstExtension created
|
||||||
|
FirstExtension.beforeAll DuplicateFixture
|
||||||
|
FirstExtension.beforeEach test()
|
||||||
|
test
|
||||||
|
FirstExtension.afterEach test()
|
||||||
|
FirstExtension.afterAll DuplicateFixture
|
||||||
|
-- results
|
||||||
|
test() -> SUCCESSFUL
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
@ExtendWith (LevelsFixture, output 01): extension instances created
|
||||||
|
FirstExtension created
|
||||||
|
SecondExtension created
|
||||||
|
|
||||||
|
@RegisterExtension with a constructor argument (RegisterExtensionFixture)
|
||||||
|
>>> EXTENSION: Initializing directory at /custom/path/logs
|
||||||
|
Using directory: /custom/path/logs
|
||||||
|
>>> EXTENSION: Cleaning up directory at /custom/path/logs
|
||||||
|
-- results
|
||||||
|
testLogCreation() -> SUCCESSFUL
|
||||||
|
|
||||||
|
ServiceLoader, junit.jupiter.extensions.autodetection.enabled not set (PlainFixture)
|
||||||
|
test
|
||||||
|
-- results
|
||||||
|
test() -> SUCCESSFUL
|
||||||
|
|
||||||
|
ServiceLoader, junit.jupiter.extensions.autodetection.enabled=true (PlainFixture)
|
||||||
|
AutoRegisteredExtension.beforeEach test()
|
||||||
|
test
|
||||||
|
-- results
|
||||||
|
test() -> SUCCESSFUL
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
TimingFixture (@ExtendWith(TimingExtension.class))
|
||||||
|
TimingExtension.beforeEach fast()
|
||||||
|
test fast
|
||||||
|
TimingExtension.afterEach fast() took N ms
|
||||||
|
TimingExtension.beforeEach slow()
|
||||||
|
test slow (slept 30 ms)
|
||||||
|
TimingExtension.afterEach slow() took N ms
|
||||||
|
-- results
|
||||||
|
fast() -> SUCCESSFUL
|
||||||
|
slow() -> SUCCESSFUL
|
||||||
|
|
||||||
|
ComposedFixture (@TimedTest = @Test + @ExtendWith(TimingExtension))
|
||||||
|
TimingExtension.beforeEach timedWithOneAnnotation()
|
||||||
|
test timedWithOneAnnotation
|
||||||
|
TimingExtension.afterEach timedWithOneAnnotation() took N ms
|
||||||
|
-- results
|
||||||
|
timedWithOneAnnotation() -> SUCCESSFUL
|
||||||
|
|
||||||
|
(the millisecond figure is masked as N; the test asserts that slow() took at least 30 ms)
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
ResolverFixture (@ExtendWith(ApiKeyResolver.class) on the class)
|
||||||
|
ApiKeyResolver.resolveParameter parameter 0 -> key for 'default'
|
||||||
|
test got sk-test-default
|
||||||
|
ApiKeyResolver.resolveParameter parameter 0 -> key for 'payments'
|
||||||
|
test got sk-test-payments
|
||||||
|
-- results
|
||||||
|
unannotatedParameter(String) -> FAILED (ParameterResolutionException: No ParameterResolver registered for parameter [java.lang.String arg0] in method [void com.ankurm.tutorials.junit.extendwith.fixtures.ResolverFixture.unannotatedParameter(java.lang.String)].)
|
||||||
|
defaultKey(String) -> SUCCESSFUL
|
||||||
|
namedKey(String) -> SUCCESSFUL
|
||||||
|
|
||||||
|
CompetingResolversFixture (two resolvers both support the parameter)
|
||||||
|
-- results
|
||||||
|
ambiguous(String) -> FAILED (ParameterResolutionException: Discovered multiple competing ParameterResolvers for parameter [java.lang.String arg0] in method [void com.ankurm.tutorials.junit.extendwith.fixtures.CompetingResolversFixture.ambiguous(java.lang.String)]: com.ankurm.tutorials.junit.extendwith.ext.ApiKeyResolver@HASH, com.ankurm.tutorials.junit.extendwith.ext.OtherApiKeyResolver@HASH)
|
||||||
|
|
||||||
|
(object hash codes in the last message are masked as @HASH)
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
ExceptionHandlerFixture (@ExtendWith(NetworkTimeoutHandler.class))
|
||||||
|
test passes
|
||||||
|
NetworkTimeoutHandler swallowed NetworkTimeoutException in remoteServiceTimesOut()
|
||||||
|
NetworkTimeoutHandler rethrowing AssertionFailedError in assertionStillFails()
|
||||||
|
NetworkTimeoutHandler rethrowing IllegalStateException in realBug()
|
||||||
|
-- results
|
||||||
|
passes() -> SUCCESSFUL
|
||||||
|
remoteServiceTimesOut() -> ABORTED (TestAbortedException: remote service unavailable: no answer from payments after 2000 ms)
|
||||||
|
assertionStillFails() -> FAILED (AssertionFailedError: expected: <4> but was: <5>)
|
||||||
|
realBug() -> FAILED (IllegalStateException: total is negative)
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
@ExtendWith @Target = [FIELD, METHOD, PARAMETER, TYPE]
|
||||||
|
@ExtendWith @Repeatable = Extensions
|
||||||
|
@ExtendWith @Inherited = true
|
||||||
|
@Extensions @Target = [FIELD, METHOD, PARAMETER, TYPE]
|
||||||
|
@RegisterExtension @Target = [FIELD]
|
||||||
|
@ExtendWith value() type = Class[]
|
||||||
|
StackedFixture has two @ExtendWith; the compiler stored them as one @Extensions
|
||||||
|
ApiKeyResolver.class.getInterfaces() = [ParameterResolver]
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
OriginalExamplesFixture (PerformanceTrackerExtension, TransactionalExtension)
|
||||||
|
>>> PERFORMANCE: Test [myTest()] took N ms
|
||||||
|
>>> DB: Starting Transaction for testUserSave()
|
||||||
|
Executing: Saving User to DB
|
||||||
|
>>> DB: Rolling back Transaction for testUserSave()
|
||||||
|
-- results
|
||||||
|
myTest() -> SUCCESSFUL
|
||||||
|
testUserSave() -> SUCCESSFUL
|
||||||
|
|
||||||
|
RegisterExtensionFixture (TempDirectoryExtension)
|
||||||
|
>>> EXTENSION: Initializing directory at /custom/path/logs
|
||||||
|
Using directory: /custom/path/logs
|
||||||
|
>>> EXTENSION: Cleaning up directory at /custom/path/logs
|
||||||
|
-- results
|
||||||
|
testLogCreation() -> SUCCESSFUL
|
||||||
|
|
||||||
|
(the millisecond figure is masked as N; the fixture sleeps 42 ms and the test asserts at least 42)
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
<?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>com.ankurm</groupId>
|
||||||
|
<artifactId>extendwith</artifactId>
|
||||||
|
<version>1.0.0</version>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
<name>extendwith</name>
|
||||||
|
<description>JUnit @ExtendWith and the Jupiter extension model: first extensions, registration, ordering. JUnit 6.1.3 by default, JUnit 5.14.4 via -Pjunit5.</description>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<maven.compiler.release>25</maven.compiler.release>
|
||||||
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
<junit.version>6.1.3</junit.version>
|
||||||
|
<!-- JUnit 5 numbers the Platform 1.x, JUnit 6 numbers it 6.x -->
|
||||||
|
<junit.platform.version>6.1.3</junit.platform.version>
|
||||||
|
<extendwith.output>output</extendwith.output>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.jupiter</groupId>
|
||||||
|
<artifactId>junit-jupiter</artifactId>
|
||||||
|
<version>${junit.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<!-- the tests start the JUnit Platform themselves (Runner), so the launcher API is on the compile classpath -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.platform</groupId>
|
||||||
|
<artifactId>junit-platform-launcher</artifactId>
|
||||||
|
<version>${junit.platform.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.mockito</groupId>
|
||||||
|
<artifactId>mockito-junit-jupiter</artifactId>
|
||||||
|
<version>5.24.0</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.assertj</groupId>
|
||||||
|
<artifactId>assertj-core</artifactId>
|
||||||
|
<version>3.27.7</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<profiles>
|
||||||
|
<!-- same sources, JUnit 5 latest: mvn -Pjunit5 test (writes output/junit5/ instead of output/) -->
|
||||||
|
<profile>
|
||||||
|
<id>junit5</id>
|
||||||
|
<properties>
|
||||||
|
<junit.version>5.14.4</junit.version>
|
||||||
|
<junit.platform.version>1.14.4</junit.platform.version>
|
||||||
|
<extendwith.output>output/junit5</extendwith.output>
|
||||||
|
</properties>
|
||||||
|
</profile>
|
||||||
|
</profiles>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<version>3.6.0</version>
|
||||||
|
<configuration>
|
||||||
|
<!-- fixtures are test classes that are meant to fail or abort: only Runner runs them -->
|
||||||
|
<excludes>
|
||||||
|
<exclude>**/fixtures/**</exclude>
|
||||||
|
</excludes>
|
||||||
|
<useManifestOnlyJar>false</useManifestOnlyJar>
|
||||||
|
<systemPropertyVariables>
|
||||||
|
<extendwith.output>${extendwith.output}</extendwith.output>
|
||||||
|
</systemPropertyVariables>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Regenerates every file under output/:
|
||||||
|
# 01-08 from the tests on JUnit 6.1.3 (mvn test)
|
||||||
|
# output/junit5/01-08 the same tests on JUnit 5.14.4 (mvn -Pjunit5 test)
|
||||||
|
# 09-10 from javap/javac probes (scripts/versions.sh)
|
||||||
|
# 11 diff of 01-08 between the two JUnit versions
|
||||||
|
# Needs JDK 17+ (built on 25), Maven, and network access to Maven Central.
|
||||||
|
set -euo pipefail
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
mvn -q -B test 2>&1 | grep -E "Tests run:|BUILD|FAIL|ERROR" || true
|
||||||
|
mvn -q -B -Pjunit5 test 2>&1 | grep -E "Tests run:|BUILD|FAIL|ERROR" || true
|
||||||
|
bash scripts/versions.sh >/dev/null
|
||||||
|
{
|
||||||
|
echo "diff -r output output/junit5 (files 01-08; JUnit 6.1.3 on the left, JUnit 5.14.4 on the right)"
|
||||||
|
if diff -r -x junit5 -x '09*' -x '10*' -x '11*' -x '12*' -x '13*' output output/junit5; then
|
||||||
|
echo "no differences: all 8 transcripts are byte-for-byte identical"
|
||||||
|
fi
|
||||||
|
} > output/11-junit5-diff.txt
|
||||||
|
ls output
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Writes output/09-junit5-vs-6.txt (what differs for extension authors between 5.14.4 and 6.1.3, by javap and javac)
|
||||||
|
# and output/10-composed-annotations.txt (which popular annotations are @ExtendWith under the hood).
|
||||||
|
# Needs JDK 17+, Maven and network access to Maven Central.
|
||||||
|
set -euo pipefail
|
||||||
|
# the sandbox sets JAVA_TOOL_OPTIONS for its proxy; javap/javac would echo a banner into the evidence files
|
||||||
|
javap() { env -u JAVA_TOOL_OPTIONS javap "$@"; }
|
||||||
|
javac() { env -u JAVA_TOOL_OPTIONS javac "$@"; }
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
OUT=output; mkdir -p "$OUT" target/probe
|
||||||
|
V5=5.14.4; V6=6.1.3
|
||||||
|
MC=https://repo1.maven.org/maven2
|
||||||
|
|
||||||
|
fetch() { # group-path artifact version -> target/probe/<artifact>-<version>.jar
|
||||||
|
local f="target/probe/$2-$3.jar"
|
||||||
|
[ -s "$f" ] || curl -sfL --retry 5 --retry-delay 3 -o "$f" "$MC/$1/$2/$3/$2-$3.jar"
|
||||||
|
echo "$f"
|
||||||
|
}
|
||||||
|
|
||||||
|
API5=$(fetch org/junit/jupiter junit-jupiter-api $V5)
|
||||||
|
API6=$(fetch org/junit/jupiter junit-jupiter-api $V6)
|
||||||
|
mvn -q -B dependency:build-classpath -Dmdep.outputFile=target/probe/cp6.txt >/dev/null
|
||||||
|
mvn -q -B -Pjunit5 dependency:build-classpath -Dmdep.outputFile=target/probe/cp5.txt >/dev/null
|
||||||
|
|
||||||
|
{
|
||||||
|
echo "== Class-file version of ExtendWith.class (major 52 = Java 8, 61 = Java 17)"
|
||||||
|
for v in $V5 $V6; do
|
||||||
|
unzip -p target/probe/junit-jupiter-api-$v.jar org/junit/jupiter/api/extension/ExtendWith.class > target/probe/ExtendWith-$v.class
|
||||||
|
echo "junit-jupiter-api $v: $(javap -v target/probe/ExtendWith-$v.class | grep 'major version' | sed 's/^ *//')"
|
||||||
|
done
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "== ExtensionContext.Store: getOrComputeIfAbsent and computeIfAbsent"
|
||||||
|
for v in $V5 $V6; do
|
||||||
|
echo "-- junit-jupiter-api $v"
|
||||||
|
javap -cp target/probe/junit-jupiter-api-$v.jar 'org.junit.jupiter.api.extension.ExtensionContext$Store' | grep -E 'ComputeIfAbsent|computeIfAbsent' | sed 's/^ *//' || true
|
||||||
|
done
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "== InvocationInterceptor.interceptDynamicTest"
|
||||||
|
for v in $V5 $V6; do
|
||||||
|
echo "-- junit-jupiter-api $v"
|
||||||
|
javap -cp target/probe/junit-jupiter-api-$v.jar org.junit.jupiter.api.extension.InvocationInterceptor | grep interceptDynamicTest | sed -e 's/^ *//' -e 's/org.junit.jupiter.api.extension.//g' -e 's/ throws java.lang.Throwable//' || true
|
||||||
|
done
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "== A Store call compiled with -Xlint:deprecation (StoreProbe.java)"
|
||||||
|
mkdir -p target/probe/src
|
||||||
|
cat > target/probe/src/StoreProbe.java <<'JAVA'
|
||||||
|
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||||
|
|
||||||
|
class StoreProbe {
|
||||||
|
Object old(ExtensionContext.Store store) {
|
||||||
|
return store.getOrComputeIfAbsent("k", k -> "v");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
JAVA
|
||||||
|
for v in 5 6; do
|
||||||
|
echo "-- against JUnit $([ $v = 5 ] && echo $V5 || echo $V6)"
|
||||||
|
javac --release 17 -Xlint:deprecation -d target/probe/classes$v -cp "$(cat target/probe/cp$v.txt)" target/probe/src/StoreProbe.java 2>&1 | grep -v 'JAVA_TOOL_OPTIONS' | sed "s|target/probe/src/||" || true
|
||||||
|
echo " javac exit status: ${PIPESTATUS[0]}"
|
||||||
|
done
|
||||||
|
cat > target/probe/src/ComputeProbe.java <<'JAVA'
|
||||||
|
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||||
|
|
||||||
|
class ComputeProbe {
|
||||||
|
Object replacement(ExtensionContext.Store store) {
|
||||||
|
return store.computeIfAbsent("k", k -> "v");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
JAVA
|
||||||
|
echo "-- the 6.x replacement computeIfAbsent (ComputeProbe.java)"
|
||||||
|
for v in 5 6; do
|
||||||
|
set +e
|
||||||
|
res=$(javac --release 17 -Xlint:deprecation -d target/probe/classes$v -cp "$(cat target/probe/cp$v.txt)" target/probe/src/ComputeProbe.java 2>&1 | grep -v 'JAVA_TOOL_OPTIONS')
|
||||||
|
rc=$?
|
||||||
|
set -e
|
||||||
|
javac --release 17 -d target/probe/classes$v -cp "$(cat target/probe/cp$v.txt)" target/probe/src/ComputeProbe.java >/dev/null 2>&1 && st=0 || st=$?
|
||||||
|
echo " against JUnit $([ $v = 5 ] && echo $V5 || echo $V6): javac exit status $st"
|
||||||
|
echo "$res" | sed 's/^/ /' | grep -v '^ *$' | head -3 || true
|
||||||
|
done
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "== The module's extensions (src/test/java/.../ext) compiled unchanged with --release 17"
|
||||||
|
for v in 5 6; do
|
||||||
|
rm -rf target/probe/ext$v
|
||||||
|
javac --release 17 -d target/probe/ext$v -cp "$(cat target/probe/cp$v.txt)" src/test/java/com/ankurm/tutorials/junit/extendwith/ext/*.java 2>&1 | grep -v 'JAVA_TOOL_OPTIONS' || true
|
||||||
|
echo " JUnit $([ $v = 5 ] && echo $V5 || echo $V6): $(ls target/probe/ext$v/com/ankurm/tutorials/junit/extendwith/ext/*.class | wc -l) class files, javac exit status ${PIPESTATUS[0]}"
|
||||||
|
done
|
||||||
|
} > "$OUT/09-junit5-vs-6.txt" 2>&1
|
||||||
|
|
||||||
|
# ---- composed annotations
|
||||||
|
MOCKITO_V=5.24.0; SPRING_V=7.0.10
|
||||||
|
MJ=$(fetch org/mockito mockito-junit-jupiter $MOCKITO_V)
|
||||||
|
echo "mockito $MOCKITO_V spring-test $SPRING_V" >&2
|
||||||
|
ST=$(fetch org/springframework spring-test $SPRING_V)
|
||||||
|
SBV=$(curl -sf $MC/org/springframework/boot/spring-boot-test/maven-metadata.xml | tr '<' '\n' | grep -E '^version>4' | sed 's/^version>//' | grep -vE -- '-M|-RC|-SNAPSHOT' | tail -1)
|
||||||
|
SB=$(fetch org/springframework/boot spring-boot-test $SBV)
|
||||||
|
{
|
||||||
|
echo "== Is the annotation itself an @ExtendWith? (javap -v, RuntimeVisibleAnnotations)"
|
||||||
|
show() { # jar class label
|
||||||
|
echo "-- $3 ($(basename "$1"))"
|
||||||
|
javap -v -cp "$1" "$2" 2>/dev/null | grep -E 'Utf8 +L.*(ExtendWith|SpringExtension|MockitoExtension)' | sed 's/^ *#[0-9]* = Utf8 *//' || true
|
||||||
|
}
|
||||||
|
show "$MJ" org.mockito.junit.jupiter.MockitoSettings "@MockitoSettings"
|
||||||
|
show "$ST" org.springframework.test.context.junit.jupiter.SpringJUnitConfig "@SpringJUnitConfig"
|
||||||
|
show "$SB" org.springframework.boot.test.context.SpringBootTest "@SpringBootTest"
|
||||||
|
} > "$OUT/10-composed-annotations.txt" 2>&1
|
||||||
|
|
||||||
|
# ---- the Spring snippet of the 2026 article: compiled only, never run
|
||||||
|
SPRING_CP="$ST:$SB:$MJ:$(cat target/probe/cp6.txt):$(fetch org/mockito mockito-core $MOCKITO_V 2>/dev/null || true)"
|
||||||
|
{
|
||||||
|
echo "== src/spring/UserProfileServiceTest.java compiled against spring-test $SPRING_V, spring-boot-test $SBV, mockito-junit-jupiter $MOCKITO_V, JUnit $V6"
|
||||||
|
rm -rf target/probe/spring; set +e
|
||||||
|
javac --release 17 -proc:none -d target/probe/spring -cp "$SPRING_CP" src/spring/UserProfileServiceTest.java 2>&1
|
||||||
|
echo "javac exit status: $?"
|
||||||
|
set -e
|
||||||
|
echo "(compiled only: running it would need a Spring Boot application class and context)"
|
||||||
|
} > "$OUT/12-spring-snippet-compile.txt" 2>&1
|
||||||
|
ls "$OUT"
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The 2026 article's "multiple extensions" snippet, verbatim apart from the imports and the stub below.
|
||||||
|
* Compiled by scripts/versions.sh, NOT executed: running it needs a Spring Boot application class and context.
|
||||||
|
*/
|
||||||
|
@ExtendWith(SpringExtension.class)
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
@SpringBootTest
|
||||||
|
class UserProfileServiceTest {
|
||||||
|
|
||||||
|
interface ExternalService {
|
||||||
|
}
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private ExternalService externalService;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testWithSpringAndMockito() {
|
||||||
|
// Test logic
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,232 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith;
|
||||||
|
|
||||||
|
import com.ankurm.tutorials.junit.extendwith.Runner.Run;
|
||||||
|
import com.ankurm.tutorials.junit.extendwith.fixtures.*;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.junit.jupiter.api.extension.Extensions;
|
||||||
|
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||||
|
|
||||||
|
import java.lang.annotation.Annotation;
|
||||||
|
import java.lang.annotation.ElementType;
|
||||||
|
import java.lang.annotation.Inherited;
|
||||||
|
import java.lang.annotation.Repeatable;
|
||||||
|
import java.lang.annotation.Target;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
/** Every test here writes one output/NN-*.txt file and asserts what the article says about it. */
|
||||||
|
class ExtendWithTest {
|
||||||
|
|
||||||
|
private static Class<?> fixture(String name) {
|
||||||
|
try {
|
||||||
|
return Class.forName("com.ankurm.tutorials.junit.extendwith.fixtures." + name);
|
||||||
|
} catch (ClassNotFoundException e) {
|
||||||
|
throw new IllegalStateException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String section(String title, Run run) {
|
||||||
|
return title + "\n" + run.text();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int indexOf(Run run, String prefix) {
|
||||||
|
for (int i = 0; i < run.events().size(); i++) {
|
||||||
|
if (run.events().get(i).startsWith(prefix)) {
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new AssertionError(prefix + " not in " + run.events());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** timings vary from run to run: the transcript keeps the shape and masks the number */
|
||||||
|
private static String maskMillis(String text) {
|
||||||
|
return text.replaceAll("took \\d+ ms", "took N ms");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String noHashes(String text) {
|
||||||
|
return text.replaceAll("@[0-9a-f]{5,8}", "@HASH");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 01 class, method, nested, parameter
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whereExtendWithCanGo() {
|
||||||
|
Run levels = Runner.run(LevelsFixture.class);
|
||||||
|
Run parameter = Runner.run(ParameterLevelFixture.class);
|
||||||
|
Transcript.write("01-levels.txt",
|
||||||
|
section("LevelsFixture (@ExtendWith(FirstExtension) on the class; SecondExtension on one method)", levels)
|
||||||
|
+ "\n\n" + section("ParameterLevelFixture (@ExtendWith(ApiKeyResolver) on the parameter itself)", parameter));
|
||||||
|
|
||||||
|
// method level: SecondExtension only runs for methodLevelToo
|
||||||
|
assertThat(levels.events().stream().filter(e -> e.startsWith("SecondExtension.beforeEach")).count()).isEqualTo(1);
|
||||||
|
// class-level extension covers the nested class: three tests, three beforeEach calls
|
||||||
|
assertThat(levels.events().stream().filter(e -> e.startsWith("FirstExtension.beforeEach")).count()).isEqualTo(3);
|
||||||
|
assertThat(parameter.events()).contains(" test got sk-test-billing");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 02 order
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void registrationOrder() {
|
||||||
|
Run stacked = Runner.run(StackedFixture.class);
|
||||||
|
Run array = Runner.run(ArrayFixture.class);
|
||||||
|
Run registered = Runner.run(RegisterExtensionOrderFixture.class);
|
||||||
|
Run mixed = Runner.run(MixedFixture.class);
|
||||||
|
Run duplicate = Runner.run(DuplicateFixture.class);
|
||||||
|
Transcript.write("02-order.txt",
|
||||||
|
section("StackedFixture @ExtendWith(First) then @ExtendWith(Second)", stacked)
|
||||||
|
+ "\n\n" + section("ArrayFixture @ExtendWith({Second, First})", array)
|
||||||
|
+ "\n\n" + section("RegisterExtensionOrderFixture first=@Order(2), second=@Order(1)", registered)
|
||||||
|
+ "\n\n" + section("MixedFixture @ExtendWith(Second) on the class, @RegisterExtension First field", mixed)
|
||||||
|
+ "\n\n" + section("DuplicateFixture @ExtendWith(First) on the class AND on the method", duplicate));
|
||||||
|
|
||||||
|
// before-callbacks in registration order, after-callbacks in reverse
|
||||||
|
assertThat(indexOf(stacked, "FirstExtension.beforeEach")).isLessThan(indexOf(stacked, "SecondExtension.beforeEach"));
|
||||||
|
assertThat(indexOf(stacked, "SecondExtension.afterEach")).isLessThan(indexOf(stacked, "FirstExtension.afterEach"));
|
||||||
|
assertThat(indexOf(array, "SecondExtension.beforeEach")).isLessThan(indexOf(array, "FirstExtension.beforeEach"));
|
||||||
|
assertThat(indexOf(registered, "SecondExtension.beforeEach")).isLessThan(indexOf(registered, "FirstExtension.beforeEach"));
|
||||||
|
// the same extension class declared twice is registered once
|
||||||
|
assertThat(duplicate.events().stream().filter(e -> e.equals("FirstExtension created")).count()).isEqualTo(1);
|
||||||
|
assertThat(duplicate.events().stream().filter(e -> e.startsWith("FirstExtension.beforeEach")).count()).isEqualTo(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 03 registration styles
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void declarativeProgrammaticAndServiceLoader() {
|
||||||
|
Run declarative = Runner.run(LevelsFixture.class);
|
||||||
|
Run programmatic = Runner.run(RegisterExtensionFixture.class);
|
||||||
|
Run autoOff = Runner.run(PlainFixture.class);
|
||||||
|
Run autoOn = Runner.run(PlainFixture.class, "junit.jupiter.extensions.autodetection.enabled", "true");
|
||||||
|
Transcript.write("03-registration.txt",
|
||||||
|
"@ExtendWith (LevelsFixture, output 01): extension instances created\n"
|
||||||
|
+ declarative.events().stream().filter(e -> e.endsWith("Extension created")).map(e -> " " + e).collect(java.util.stream.Collectors.joining("\n"))
|
||||||
|
+ "\n\n" + section("@RegisterExtension with a constructor argument (RegisterExtensionFixture)", programmatic)
|
||||||
|
+ "\n\n" + section("ServiceLoader, junit.jupiter.extensions.autodetection.enabled not set (PlainFixture)", autoOff)
|
||||||
|
+ "\n\n" + section("ServiceLoader, junit.jupiter.extensions.autodetection.enabled=true (PlainFixture)", autoOn));
|
||||||
|
|
||||||
|
assertThat(programmatic.events()).containsExactly(
|
||||||
|
">>> EXTENSION: Initializing directory at /custom/path/logs",
|
||||||
|
"Using directory: /custom/path/logs",
|
||||||
|
">>> EXTENSION: Cleaning up directory at /custom/path/logs");
|
||||||
|
assertThat(autoOff.events()).noneMatch(e -> e.startsWith("AutoRegisteredExtension"));
|
||||||
|
assertThat(autoOn.events()).anyMatch(e -> e.startsWith("AutoRegisteredExtension.beforeEach"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 04 first extension: timing
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void firstExtensionTiming() {
|
||||||
|
Run timing = Runner.run(TimingFixture.class);
|
||||||
|
Run composed = Runner.run(ComposedFixture.class);
|
||||||
|
Transcript.write("04-timing-extension.txt", maskMillis(
|
||||||
|
section("TimingFixture (@ExtendWith(TimingExtension.class))", timing)
|
||||||
|
+ "\n\n" + section("ComposedFixture (@TimedTest = @Test + @ExtendWith(TimingExtension))", composed))
|
||||||
|
+ "\n\n(the millisecond figure is masked as N; the test asserts that slow() took at least 30 ms)");
|
||||||
|
|
||||||
|
Matcher m = Pattern.compile("TimingExtension.afterEach\\s+slow\\(\\) took (\\d+) ms")
|
||||||
|
.matcher(String.join("\n", timing.events()));
|
||||||
|
assertThat(m.find()).isTrue();
|
||||||
|
assertThat(Long.parseLong(m.group(1))).isGreaterThanOrEqualTo(30);
|
||||||
|
assertThat(composed.events()).anyMatch(e -> e.startsWith("TimingExtension.afterEach"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 05 parameter resolver
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void parameterResolver() {
|
||||||
|
Run ok = Runner.run(ResolverFixture.class);
|
||||||
|
Run competing = Runner.run(CompetingResolversFixture.class);
|
||||||
|
Transcript.write("05-parameter-resolver.txt", noHashes(
|
||||||
|
section("ResolverFixture (@ExtendWith(ApiKeyResolver.class) on the class)", ok)
|
||||||
|
+ "\n\n" + section("CompetingResolversFixture (two resolvers both support the parameter)", competing))
|
||||||
|
+ "\n\n(object hash codes in the last message are masked as @HASH)");
|
||||||
|
|
||||||
|
assertThat(ok.events()).contains(" test got sk-test-default", " test got sk-test-payments");
|
||||||
|
assertThat(ok.results()).anyMatch(r -> r.startsWith("unannotatedParameter") && r.contains("ParameterResolutionException"));
|
||||||
|
assertThat(competing.results()).anyMatch(r -> r.contains("competing ParameterResolvers"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 06 exception handler
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testExecutionExceptionHandler() {
|
||||||
|
Run run = Runner.run(ExceptionHandlerFixture.class);
|
||||||
|
Transcript.write("06-exception-handler.txt", section("ExceptionHandlerFixture (@ExtendWith(NetworkTimeoutHandler.class))", run));
|
||||||
|
|
||||||
|
assertThat(run.results()).anyMatch(r -> r.startsWith("remoteServiceTimesOut()") && r.contains("ABORTED"));
|
||||||
|
assertThat(run.results()).anyMatch(r -> r.startsWith("realBug()") && r.contains("FAILED"));
|
||||||
|
assertThat(run.results()).anyMatch(r -> r.startsWith("assertionStillFails()") && r.contains("FAILED"));
|
||||||
|
assertThat(run.results()).anyMatch(r -> r.startsWith("passes()") && r.contains("SUCCESSFUL"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 07 the annotation itself
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void theAnnotationItself() {
|
||||||
|
List<String> lines = new ArrayList<>();
|
||||||
|
Target target = ExtendWith.class.getAnnotation(Target.class);
|
||||||
|
lines.add("@ExtendWith @Target = " + Arrays.stream(target.value()).map(ElementType::name).sorted().toList());
|
||||||
|
lines.add("@ExtendWith @Repeatable = " + ExtendWith.class.getAnnotation(Repeatable.class).value().getSimpleName());
|
||||||
|
lines.add("@ExtendWith @Inherited = " + ExtendWith.class.isAnnotationPresent(Inherited.class));
|
||||||
|
lines.add("@Extensions @Target = " + Arrays.stream(Extensions.class.getAnnotation(Target.class).value()).map(ElementType::name).sorted().toList());
|
||||||
|
lines.add("@RegisterExtension @Target = " + Arrays.stream(RegisterExtension.class.getAnnotation(Target.class).value()).map(ElementType::name).toList());
|
||||||
|
lines.add("@ExtendWith value() type = " + ExtendWith.class.getDeclaredMethods()[0].getReturnType().getSimpleName());
|
||||||
|
Class<?> stacked = StackedFixture.class;
|
||||||
|
Annotation container = Arrays.stream(stacked.getAnnotations()).filter(a -> a instanceof Extensions).findFirst().orElseThrow();
|
||||||
|
lines.add("StackedFixture has two @ExtendWith; the compiler stored them as one @" + container.annotationType().getSimpleName());
|
||||||
|
lines.add("ApiKeyResolver.class.getInterfaces() = " + Arrays.stream(ApiKeyResolverProbe.interfaces()).map(Class::getSimpleName).toList());
|
||||||
|
Transcript.write("07-annotation-facts.txt", String.join("\n", lines));
|
||||||
|
|
||||||
|
assertThat(target.value()).contains(ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER);
|
||||||
|
assertThat(ExtendWith.class.isAnnotationPresent(Inherited.class)).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** tiny helper so the facts file can list the extension points a class implements */
|
||||||
|
static final class ApiKeyResolverProbe {
|
||||||
|
static Class<?>[] interfaces() {
|
||||||
|
return com.ankurm.tutorials.junit.extendwith.ext.ApiKeyResolver.class.getInterfaces();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 08 the 2026 article's examples, run for real
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void originalArticleExamples() {
|
||||||
|
Run original = Runner.run(OriginalExamplesFixture.class);
|
||||||
|
Run tempDir = Runner.run(RegisterExtensionFixture.class);
|
||||||
|
Transcript.write("08-original-examples.txt", maskMillis(
|
||||||
|
section("OriginalExamplesFixture (PerformanceTrackerExtension, TransactionalExtension)", original)
|
||||||
|
+ "\n\n" + section("RegisterExtensionFixture (TempDirectoryExtension)", tempDir))
|
||||||
|
+ "\n\n(the millisecond figure is masked as N; the fixture sleeps 42 ms and the test asserts at least 42)");
|
||||||
|
|
||||||
|
Matcher m = Pattern.compile("took (\\d+) ms").matcher(String.join("\n", original.events()));
|
||||||
|
assertThat(m.find()).isTrue();
|
||||||
|
assertThat(Long.parseLong(m.group(1))).isGreaterThanOrEqualTo(42);
|
||||||
|
assertThat(original.events()).contains(
|
||||||
|
">>> DB: Starting Transaction for testUserSave()",
|
||||||
|
"Executing: Saving User to DB",
|
||||||
|
">>> DB: Rolling back Transaction for testUserSave()");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 13 lifecycle order
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void lifecycleOrder() {
|
||||||
|
Run run = Runner.run(LifecycleFixture.class);
|
||||||
|
Transcript.write("13-lifecycle-order.txt", section("LifecycleFixture (LifecycleExtension + the class's own @BeforeAll/@BeforeEach/@AfterEach/@AfterAll)", run));
|
||||||
|
|
||||||
|
assertThat(run.events()).containsExactly(
|
||||||
|
"BeforeAllCallback", " @BeforeAll",
|
||||||
|
"BeforeEachCallback", " @BeforeEach",
|
||||||
|
"BeforeTestExecutionCallback", " @Test", "AfterTestExecutionCallback",
|
||||||
|
" @AfterEach", "AfterEachCallback",
|
||||||
|
" @AfterAll", "AfterAllCallback");
|
||||||
|
}
|
||||||
|
}
|
||||||
+44
@@ -0,0 +1,44 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.InjectMocks;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
/** The 2026 article's Mockito example. The article never showed PaymentGateway and OrderService; they are minimal stand-ins. */
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
class MockitoOrderServiceTest {
|
||||||
|
|
||||||
|
interface PaymentGateway {
|
||||||
|
boolean authorize(double amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
static class OrderService {
|
||||||
|
private final PaymentGateway gateway;
|
||||||
|
|
||||||
|
OrderService(PaymentGateway gateway) {
|
||||||
|
this.gateway = gateway;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean processOrder(double amount) {
|
||||||
|
return gateway.authorize(amount);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private PaymentGateway paymentGateway;
|
||||||
|
|
||||||
|
@InjectMocks
|
||||||
|
private OrderService orderService;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldProcessPaymentSuccessfully() {
|
||||||
|
when(paymentGateway.authorize(100.0)).thenReturn(true);
|
||||||
|
boolean result = orderService.processOrder(100.0);
|
||||||
|
assertTrue(result, "Payment should be authorized");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith;
|
||||||
|
|
||||||
|
import com.ankurm.tutorials.junit.extendwith.ext.EventLog;
|
||||||
|
import org.junit.platform.engine.TestExecutionResult;
|
||||||
|
import org.junit.platform.launcher.TestExecutionListener;
|
||||||
|
import org.junit.platform.launcher.TestIdentifier;
|
||||||
|
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
|
||||||
|
import org.junit.platform.launcher.core.LauncherFactory;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass;
|
||||||
|
|
||||||
|
/** Starts the JUnit Platform on one fixture class and returns what the extensions logged plus how each test ended. */
|
||||||
|
final class Runner {
|
||||||
|
|
||||||
|
record Run(List<String> events, List<String> results) {
|
||||||
|
String text() {
|
||||||
|
List<String> all = new ArrayList<>(events);
|
||||||
|
all.add("-- results");
|
||||||
|
results.forEach(r -> all.add(" " + r));
|
||||||
|
return String.join("\n", all);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Runner() {
|
||||||
|
}
|
||||||
|
|
||||||
|
static Run run(Class<?> fixture, String... configuration) {
|
||||||
|
EventLog.drain();
|
||||||
|
LauncherDiscoveryRequestBuilder request = LauncherDiscoveryRequestBuilder.request().selectors(selectClass(fixture));
|
||||||
|
for (int i = 0; i < configuration.length; i += 2) {
|
||||||
|
request.configurationParameter(configuration[i], configuration[i + 1]);
|
||||||
|
}
|
||||||
|
List<String> results = new ArrayList<>();
|
||||||
|
TestExecutionListener listener = new TestExecutionListener() {
|
||||||
|
@Override
|
||||||
|
public void executionFinished(TestIdentifier id, TestExecutionResult result) {
|
||||||
|
if (id.isTest() || result.getStatus() != TestExecutionResult.Status.SUCCESSFUL) {
|
||||||
|
String detail = result.getThrowable()
|
||||||
|
.map(t -> " (" + t.getClass().getSimpleName() + ": " + firstLine(t.getMessage()) + ")")
|
||||||
|
.orElse("");
|
||||||
|
results.add(id.getDisplayName() + " -> " + result.getStatus() + detail);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
LauncherFactory.create().execute(request.build(), listener);
|
||||||
|
return new Run(EventLog.drain(), results);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String firstLine(String message) {
|
||||||
|
return message == null ? "" : message.lines().findFirst().orElse("");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
|
||||||
|
/** Writes an evidence file under output/ (or output/junit5/ with -Pjunit5). */
|
||||||
|
final class Transcript {
|
||||||
|
|
||||||
|
private Transcript() {
|
||||||
|
}
|
||||||
|
|
||||||
|
static void write(String name, String content) {
|
||||||
|
try {
|
||||||
|
Path dir = Path.of(System.getProperty("extendwith.output", "output"));
|
||||||
|
Files.createDirectories(dir);
|
||||||
|
Files.writeString(dir.resolve(name), content.stripTrailing() + "\n");
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new IllegalStateException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith.ext;
|
||||||
|
|
||||||
|
import java.lang.annotation.ElementType;
|
||||||
|
import java.lang.annotation.Retention;
|
||||||
|
import java.lang.annotation.RetentionPolicy;
|
||||||
|
import java.lang.annotation.Target;
|
||||||
|
|
||||||
|
/** Marks a String test parameter that ApiKeyResolver should fill in. */
|
||||||
|
@Target(ElementType.PARAMETER)
|
||||||
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
|
public @interface ApiKey {
|
||||||
|
String value() default "default";
|
||||||
|
}
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith.ext;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||||
|
import org.junit.jupiter.api.extension.ParameterContext;
|
||||||
|
import org.junit.jupiter.api.extension.ParameterResolver;
|
||||||
|
|
||||||
|
/** Second extension of the article: it hands a value to any String parameter annotated @ApiKey. */
|
||||||
|
public class ApiKeyResolver implements ParameterResolver {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
|
||||||
|
return parameterContext.isAnnotated(ApiKey.class)
|
||||||
|
&& parameterContext.getParameter().getType() == String.class;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
|
||||||
|
String name = parameterContext.findAnnotation(ApiKey.class).orElseThrow().value();
|
||||||
|
EventLog.add("ApiKeyResolver.resolveParameter parameter " + parameterContext.getIndex() + " -> key for '" + name + "'");
|
||||||
|
return "sk-test-" + name;
|
||||||
|
}
|
||||||
|
}
|
||||||
+13
@@ -0,0 +1,13 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith.ext;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.extension.BeforeEachCallback;
|
||||||
|
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||||
|
|
||||||
|
/** Registered by ServiceLoader (src/test/resources/META-INF/services/...Extension), only when auto-detection is switched on. */
|
||||||
|
public class AutoRegisteredExtension implements BeforeEachCallback {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void beforeEach(ExtensionContext context) {
|
||||||
|
EventLog.add("AutoRegisteredExtension.beforeEach " + context.getDisplayName());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith.ext;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/** Where every extension in this module writes what it did, so a test can print and assert the exact order. */
|
||||||
|
public final class EventLog {
|
||||||
|
|
||||||
|
private static final List<String> LINES = new ArrayList<>();
|
||||||
|
|
||||||
|
private EventLog() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static synchronized void add(String line) {
|
||||||
|
LINES.add(line);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Returns everything recorded since the last call and clears the log. */
|
||||||
|
public static synchronized List<String> drain() {
|
||||||
|
List<String> copy = List.copyOf(LINES);
|
||||||
|
LINES.clear();
|
||||||
|
return copy;
|
||||||
|
}
|
||||||
|
}
|
||||||
+35
@@ -0,0 +1,35 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith.ext;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.extension.AfterAllCallback;
|
||||||
|
import org.junit.jupiter.api.extension.AfterEachCallback;
|
||||||
|
import org.junit.jupiter.api.extension.BeforeAllCallback;
|
||||||
|
import org.junit.jupiter.api.extension.BeforeEachCallback;
|
||||||
|
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||||
|
|
||||||
|
/** Logs its four callbacks, so registration order and nesting can be read straight from the log. */
|
||||||
|
public class FirstExtension implements BeforeAllCallback, BeforeEachCallback, AfterEachCallback, AfterAllCallback {
|
||||||
|
|
||||||
|
public FirstExtension() {
|
||||||
|
EventLog.add("FirstExtension created");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void beforeAll(ExtensionContext context) {
|
||||||
|
EventLog.add("FirstExtension.beforeAll " + context.getDisplayName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void beforeEach(ExtensionContext context) {
|
||||||
|
EventLog.add("FirstExtension.beforeEach " + context.getDisplayName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void afterEach(ExtensionContext context) {
|
||||||
|
EventLog.add("FirstExtension.afterEach " + context.getDisplayName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void afterAll(ExtensionContext context) {
|
||||||
|
EventLog.add("FirstExtension.afterAll " + context.getDisplayName());
|
||||||
|
}
|
||||||
|
}
|
||||||
+44
@@ -0,0 +1,44 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith.ext;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.extension.AfterAllCallback;
|
||||||
|
import org.junit.jupiter.api.extension.AfterEachCallback;
|
||||||
|
import org.junit.jupiter.api.extension.AfterTestExecutionCallback;
|
||||||
|
import org.junit.jupiter.api.extension.BeforeAllCallback;
|
||||||
|
import org.junit.jupiter.api.extension.BeforeEachCallback;
|
||||||
|
import org.junit.jupiter.api.extension.BeforeTestExecutionCallback;
|
||||||
|
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||||
|
|
||||||
|
/** All six lifecycle callbacks in one class, logging when each one fires relative to the test class's own @BeforeEach/@AfterEach. */
|
||||||
|
public class LifecycleExtension implements BeforeAllCallback, BeforeEachCallback, BeforeTestExecutionCallback,
|
||||||
|
AfterTestExecutionCallback, AfterEachCallback, AfterAllCallback {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void beforeAll(ExtensionContext context) {
|
||||||
|
EventLog.add("BeforeAllCallback");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void beforeEach(ExtensionContext context) {
|
||||||
|
EventLog.add("BeforeEachCallback");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void beforeTestExecution(ExtensionContext context) {
|
||||||
|
EventLog.add("BeforeTestExecutionCallback");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void afterTestExecution(ExtensionContext context) {
|
||||||
|
EventLog.add("AfterTestExecutionCallback");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void afterEach(ExtensionContext context) {
|
||||||
|
EventLog.add("AfterEachCallback");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void afterAll(ExtensionContext context) {
|
||||||
|
EventLog.add("AfterAllCallback");
|
||||||
|
}
|
||||||
|
}
|
||||||
+8
@@ -0,0 +1,8 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith.ext;
|
||||||
|
|
||||||
|
/** Stand-in for "the remote service did not answer". */
|
||||||
|
public class NetworkTimeoutException extends RuntimeException {
|
||||||
|
public NetworkTimeoutException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith.ext;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||||
|
import org.junit.jupiter.api.extension.TestExecutionExceptionHandler;
|
||||||
|
import org.opentest4j.TestAbortedException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Third extension of the article: a test that dies of a network timeout is reported as aborted (not failed);
|
||||||
|
* every other exception is rethrown untouched, so real failures stay failures.
|
||||||
|
*/
|
||||||
|
public class NetworkTimeoutHandler implements TestExecutionExceptionHandler {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void handleTestExecutionException(ExtensionContext context, Throwable throwable) throws Throwable {
|
||||||
|
if (throwable instanceof NetworkTimeoutException) {
|
||||||
|
EventLog.add("NetworkTimeoutHandler swallowed " + throwable.getClass().getSimpleName() + " in " + context.getDisplayName());
|
||||||
|
throw new TestAbortedException("remote service unavailable: " + throwable.getMessage(), throwable);
|
||||||
|
}
|
||||||
|
EventLog.add("NetworkTimeoutHandler rethrowing " + throwable.getClass().getSimpleName() + " in " + context.getDisplayName());
|
||||||
|
throw throwable;
|
||||||
|
}
|
||||||
|
}
|
||||||
+19
@@ -0,0 +1,19 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith.ext;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||||
|
import org.junit.jupiter.api.extension.ParameterContext;
|
||||||
|
import org.junit.jupiter.api.extension.ParameterResolver;
|
||||||
|
|
||||||
|
/** Deliberately supports the same parameters as ApiKeyResolver, to show what JUnit does with two resolvers for one parameter. */
|
||||||
|
public class OtherApiKeyResolver implements ParameterResolver {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
|
||||||
|
return parameterContext.isAnnotated(ApiKey.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
|
||||||
|
return "other";
|
||||||
|
}
|
||||||
|
}
|
||||||
+26
@@ -0,0 +1,26 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith.ext;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.extension.AfterTestExecutionCallback;
|
||||||
|
import org.junit.jupiter.api.extension.BeforeTestExecutionCallback;
|
||||||
|
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||||
|
|
||||||
|
/** The 2026 article's "Performance Tracker", unchanged except that it writes to EventLog instead of System.out. */
|
||||||
|
public class PerformanceTrackerExtension implements BeforeTestExecutionCallback, AfterTestExecutionCallback {
|
||||||
|
private static final String START_TIME = "START_TIME";
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void beforeTestExecution(ExtensionContext context) {
|
||||||
|
getStore(context).put(START_TIME, System.currentTimeMillis());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void afterTestExecution(ExtensionContext context) {
|
||||||
|
long startTime = getStore(context).remove(START_TIME, long.class);
|
||||||
|
long duration = System.currentTimeMillis() - startTime;
|
||||||
|
EventLog.add(">>> PERFORMANCE: Test [" + context.getDisplayName() + "] took " + duration + " ms");
|
||||||
|
}
|
||||||
|
|
||||||
|
private ExtensionContext.Store getStore(ExtensionContext context) {
|
||||||
|
return context.getStore(ExtensionContext.Namespace.create(getClass(), context.getRequiredTestMethod()));
|
||||||
|
}
|
||||||
|
}
|
||||||
+35
@@ -0,0 +1,35 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith.ext;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.extension.AfterAllCallback;
|
||||||
|
import org.junit.jupiter.api.extension.AfterEachCallback;
|
||||||
|
import org.junit.jupiter.api.extension.BeforeAllCallback;
|
||||||
|
import org.junit.jupiter.api.extension.BeforeEachCallback;
|
||||||
|
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||||
|
|
||||||
|
/** Logs its four callbacks, so registration order and nesting can be read straight from the log. */
|
||||||
|
public class SecondExtension implements BeforeAllCallback, BeforeEachCallback, AfterEachCallback, AfterAllCallback {
|
||||||
|
|
||||||
|
public SecondExtension() {
|
||||||
|
EventLog.add("SecondExtension created");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void beforeAll(ExtensionContext context) {
|
||||||
|
EventLog.add("SecondExtension.beforeAll " + context.getDisplayName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void beforeEach(ExtensionContext context) {
|
||||||
|
EventLog.add("SecondExtension.beforeEach " + context.getDisplayName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void afterEach(ExtensionContext context) {
|
||||||
|
EventLog.add("SecondExtension.afterEach " + context.getDisplayName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void afterAll(ExtensionContext context) {
|
||||||
|
EventLog.add("SecondExtension.afterAll " + context.getDisplayName());
|
||||||
|
}
|
||||||
|
}
|
||||||
+32
@@ -0,0 +1,32 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith.ext;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.extension.AfterAllCallback;
|
||||||
|
import org.junit.jupiter.api.extension.BeforeAllCallback;
|
||||||
|
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The 2026 article used TempDirectoryExtension with @RegisterExtension but never showed its code.
|
||||||
|
* This version only logs: it takes a constructor argument, which is the point of @RegisterExtension, and touches no disk.
|
||||||
|
*/
|
||||||
|
public class TempDirectoryExtension implements BeforeAllCallback, AfterAllCallback {
|
||||||
|
|
||||||
|
private final String path;
|
||||||
|
|
||||||
|
public TempDirectoryExtension(String path) {
|
||||||
|
this.path = path;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPath() {
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void beforeAll(ExtensionContext context) {
|
||||||
|
EventLog.add(">>> EXTENSION: Initializing directory at " + path);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void afterAll(ExtensionContext context) {
|
||||||
|
EventLog.add(">>> EXTENSION: Cleaning up directory at " + path);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith.ext;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
|
||||||
|
import java.lang.annotation.ElementType;
|
||||||
|
import java.lang.annotation.Retention;
|
||||||
|
import java.lang.annotation.RetentionPolicy;
|
||||||
|
import java.lang.annotation.Target;
|
||||||
|
|
||||||
|
/** A composed annotation: @Test plus @ExtendWith(TimingExtension.class) under one name. */
|
||||||
|
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
|
||||||
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
|
@Test
|
||||||
|
@ExtendWith(TimingExtension.class)
|
||||||
|
public @interface TimedTest {
|
||||||
|
}
|
||||||
+29
@@ -0,0 +1,29 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith.ext;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.extension.AfterEachCallback;
|
||||||
|
import org.junit.jupiter.api.extension.BeforeEachCallback;
|
||||||
|
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||||
|
import org.junit.jupiter.api.extension.ExtensionContext.Namespace;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The first extension of the article: it times every test and reports the duration.
|
||||||
|
* Two callbacks, one piece of state, kept in the ExtensionContext.Store so it belongs to one test, not to the extension instance.
|
||||||
|
*/
|
||||||
|
public class TimingExtension implements BeforeEachCallback, AfterEachCallback {
|
||||||
|
|
||||||
|
private static final Namespace NAMESPACE = Namespace.create(TimingExtension.class);
|
||||||
|
private static final String START = "start";
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void beforeEach(ExtensionContext context) {
|
||||||
|
context.getStore(NAMESPACE).put(START, System.nanoTime());
|
||||||
|
EventLog.add("TimingExtension.beforeEach " + context.getDisplayName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void afterEach(ExtensionContext context) {
|
||||||
|
long start = context.getStore(NAMESPACE).remove(START, long.class);
|
||||||
|
long millis = (System.nanoTime() - start) / 1_000_000;
|
||||||
|
EventLog.add("TimingExtension.afterEach " + context.getDisplayName() + " took " + millis + " ms");
|
||||||
|
}
|
||||||
|
}
|
||||||
+19
@@ -0,0 +1,19 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith.ext;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.extension.AfterEachCallback;
|
||||||
|
import org.junit.jupiter.api.extension.BeforeEachCallback;
|
||||||
|
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||||
|
|
||||||
|
/** The 2026 article's "Database Transaction" extension: the begin/rollback calls are placeholders there and here. */
|
||||||
|
public class TransactionalExtension implements BeforeEachCallback, AfterEachCallback {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void beforeEach(ExtensionContext context) {
|
||||||
|
EventLog.add(">>> DB: Starting Transaction for " + context.getDisplayName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void afterEach(ExtensionContext context) {
|
||||||
|
EventLog.add(">>> DB: Rolling back Transaction for " + context.getDisplayName());
|
||||||
|
}
|
||||||
|
}
|
||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith.fixtures;
|
||||||
|
|
||||||
|
import com.ankurm.tutorials.junit.extendwith.ext.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
|
import org.junit.jupiter.api.extension.*;
|
||||||
|
import org.junit.jupiter.api.io.*;
|
||||||
|
|
||||||
|
@ExtendWith({SecondExtension.class, FirstExtension.class})
|
||||||
|
public class ArrayFixture {
|
||||||
|
@Test
|
||||||
|
void test() {
|
||||||
|
EventLog.add(" test");
|
||||||
|
}
|
||||||
|
}
|
||||||
+15
@@ -0,0 +1,15 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith.fixtures;
|
||||||
|
|
||||||
|
import com.ankurm.tutorials.junit.extendwith.ext.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
|
import org.junit.jupiter.api.extension.*;
|
||||||
|
import org.junit.jupiter.api.io.*;
|
||||||
|
|
||||||
|
@ExtendWith({ApiKeyResolver.class, OtherApiKeyResolver.class})
|
||||||
|
public class CompetingResolversFixture {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void ambiguous(@ApiKey String key) {
|
||||||
|
EventLog.add(" test never runs");
|
||||||
|
}
|
||||||
|
}
|
||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith.fixtures;
|
||||||
|
|
||||||
|
import com.ankurm.tutorials.junit.extendwith.ext.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
|
import org.junit.jupiter.api.extension.*;
|
||||||
|
import org.junit.jupiter.api.io.*;
|
||||||
|
|
||||||
|
public class ComposedFixture {
|
||||||
|
|
||||||
|
@TimedTest
|
||||||
|
void timedWithOneAnnotation() {
|
||||||
|
EventLog.add(" test timedWithOneAnnotation");
|
||||||
|
}
|
||||||
|
}
|
||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith.fixtures;
|
||||||
|
|
||||||
|
import com.ankurm.tutorials.junit.extendwith.ext.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
|
import org.junit.jupiter.api.extension.*;
|
||||||
|
import org.junit.jupiter.api.io.*;
|
||||||
|
|
||||||
|
/** The same extension class on the class and on a method. */
|
||||||
|
@ExtendWith(FirstExtension.class)
|
||||||
|
public class DuplicateFixture {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@ExtendWith(FirstExtension.class)
|
||||||
|
void test() {
|
||||||
|
EventLog.add(" test");
|
||||||
|
}
|
||||||
|
}
|
||||||
+30
@@ -0,0 +1,30 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith.fixtures;
|
||||||
|
|
||||||
|
import com.ankurm.tutorials.junit.extendwith.ext.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
|
import org.junit.jupiter.api.extension.*;
|
||||||
|
import org.junit.jupiter.api.io.*;
|
||||||
|
|
||||||
|
@ExtendWith(NetworkTimeoutHandler.class)
|
||||||
|
public class ExceptionHandlerFixture {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void remoteServiceTimesOut() {
|
||||||
|
throw new NetworkTimeoutException("no answer from payments after 2000 ms");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void realBug() {
|
||||||
|
throw new IllegalStateException("total is negative");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void assertionStillFails() {
|
||||||
|
Assertions.assertEquals(4, 2 + 2 + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void passes() {
|
||||||
|
EventLog.add(" test passes");
|
||||||
|
}
|
||||||
|
}
|
||||||
+30
@@ -0,0 +1,30 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith.fixtures;
|
||||||
|
|
||||||
|
import com.ankurm.tutorials.junit.extendwith.ext.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
|
import org.junit.jupiter.api.extension.*;
|
||||||
|
import org.junit.jupiter.api.io.*;
|
||||||
|
|
||||||
|
/** Where can @ExtendWith go? Class, method, nested class. */
|
||||||
|
@ExtendWith(FirstExtension.class)
|
||||||
|
public class LevelsFixture {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void classLevelOnly() {
|
||||||
|
EventLog.add(" test classLevelOnly");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@ExtendWith(SecondExtension.class)
|
||||||
|
void methodLevelToo() {
|
||||||
|
EventLog.add(" test methodLevelToo");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
class Inner {
|
||||||
|
@Test
|
||||||
|
void insideNested() {
|
||||||
|
EventLog.add(" test insideNested");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+39
@@ -0,0 +1,39 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith.fixtures;
|
||||||
|
|
||||||
|
import com.ankurm.tutorials.junit.extendwith.ext.EventLog;
|
||||||
|
import com.ankurm.tutorials.junit.extendwith.ext.LifecycleExtension;
|
||||||
|
import org.junit.jupiter.api.AfterAll;
|
||||||
|
import org.junit.jupiter.api.AfterEach;
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
|
||||||
|
@ExtendWith(LifecycleExtension.class)
|
||||||
|
public class LifecycleFixture {
|
||||||
|
|
||||||
|
@BeforeAll
|
||||||
|
static void beforeAll() {
|
||||||
|
EventLog.add(" @BeforeAll");
|
||||||
|
}
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void beforeEach() {
|
||||||
|
EventLog.add(" @BeforeEach");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void test() {
|
||||||
|
EventLog.add(" @Test");
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterEach
|
||||||
|
void afterEach() {
|
||||||
|
EventLog.add(" @AfterEach");
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterAll
|
||||||
|
static void afterAll() {
|
||||||
|
EventLog.add(" @AfterAll");
|
||||||
|
}
|
||||||
|
}
|
||||||
+19
@@ -0,0 +1,19 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith.fixtures;
|
||||||
|
|
||||||
|
import com.ankurm.tutorials.junit.extendwith.ext.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
|
import org.junit.jupiter.api.extension.*;
|
||||||
|
import org.junit.jupiter.api.io.*;
|
||||||
|
|
||||||
|
/** One extension declared with @ExtendWith, the other with @RegisterExtension. */
|
||||||
|
@ExtendWith(SecondExtension.class)
|
||||||
|
public class MixedFixture {
|
||||||
|
|
||||||
|
@RegisterExtension
|
||||||
|
static FirstExtension first = new FirstExtension();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void test() {
|
||||||
|
EventLog.add(" test");
|
||||||
|
}
|
||||||
|
}
|
||||||
+25
@@ -0,0 +1,25 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith.fixtures;
|
||||||
|
|
||||||
|
import com.ankurm.tutorials.junit.extendwith.ext.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
|
import org.junit.jupiter.api.extension.*;
|
||||||
|
import org.junit.jupiter.api.io.*;
|
||||||
|
|
||||||
|
/** The three examples of the 2026 article, run for real. */
|
||||||
|
public class OriginalExamplesFixture {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@ExtendWith(PerformanceTrackerExtension.class)
|
||||||
|
void myTest() throws InterruptedException {
|
||||||
|
Thread.sleep(42);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
@ExtendWith(TransactionalExtension.class)
|
||||||
|
class UserRepositoryTest {
|
||||||
|
@Test
|
||||||
|
void testUserSave() {
|
||||||
|
EventLog.add("Executing: Saving User to DB");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+15
@@ -0,0 +1,15 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith.fixtures;
|
||||||
|
|
||||||
|
import com.ankurm.tutorials.junit.extendwith.ext.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
|
import org.junit.jupiter.api.extension.*;
|
||||||
|
import org.junit.jupiter.api.io.*;
|
||||||
|
|
||||||
|
/** @ExtendWith directly on a parameter registers the resolver for that parameter only. */
|
||||||
|
public class ParameterLevelFixture {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void keyFromParameterAnnotation(@ExtendWith(ApiKeyResolver.class) @ApiKey("billing") String key) {
|
||||||
|
EventLog.add(" test got " + key);
|
||||||
|
}
|
||||||
|
}
|
||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith.fixtures;
|
||||||
|
|
||||||
|
import com.ankurm.tutorials.junit.extendwith.ext.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
|
import org.junit.jupiter.api.extension.*;
|
||||||
|
import org.junit.jupiter.api.io.*;
|
||||||
|
|
||||||
|
/** No annotations at all: only ServiceLoader auto-detection can attach an extension here. */
|
||||||
|
public class PlainFixture {
|
||||||
|
@Test
|
||||||
|
void test() {
|
||||||
|
EventLog.add(" test");
|
||||||
|
}
|
||||||
|
}
|
||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith.fixtures;
|
||||||
|
|
||||||
|
import com.ankurm.tutorials.junit.extendwith.ext.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
|
import org.junit.jupiter.api.extension.*;
|
||||||
|
import org.junit.jupiter.api.io.*;
|
||||||
|
|
||||||
|
public class RegisterExtensionFixture {
|
||||||
|
|
||||||
|
@RegisterExtension
|
||||||
|
static TempDirectoryExtension tempDir = new TempDirectoryExtension("/custom/path/logs");
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testLogCreation() {
|
||||||
|
EventLog.add("Using directory: " + tempDir.getPath());
|
||||||
|
}
|
||||||
|
}
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith.fixtures;
|
||||||
|
|
||||||
|
import com.ankurm.tutorials.junit.extendwith.ext.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
|
import org.junit.jupiter.api.extension.*;
|
||||||
|
import org.junit.jupiter.api.io.*;
|
||||||
|
|
||||||
|
public class RegisterExtensionOrderFixture {
|
||||||
|
|
||||||
|
@RegisterExtension
|
||||||
|
@Order(2)
|
||||||
|
static FirstExtension first = new FirstExtension();
|
||||||
|
|
||||||
|
@RegisterExtension
|
||||||
|
@Order(1)
|
||||||
|
static SecondExtension second = new SecondExtension();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void test() {
|
||||||
|
EventLog.add(" test");
|
||||||
|
}
|
||||||
|
}
|
||||||
+25
@@ -0,0 +1,25 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith.fixtures;
|
||||||
|
|
||||||
|
import com.ankurm.tutorials.junit.extendwith.ext.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
|
import org.junit.jupiter.api.extension.*;
|
||||||
|
import org.junit.jupiter.api.io.*;
|
||||||
|
|
||||||
|
@ExtendWith(ApiKeyResolver.class)
|
||||||
|
public class ResolverFixture {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void defaultKey(@ApiKey String key) {
|
||||||
|
EventLog.add(" test got " + key);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void namedKey(@ApiKey("payments") String key) {
|
||||||
|
EventLog.add(" test got " + key);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void unannotatedParameter(String key) {
|
||||||
|
EventLog.add(" test never runs");
|
||||||
|
}
|
||||||
|
}
|
||||||
+15
@@ -0,0 +1,15 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith.fixtures;
|
||||||
|
|
||||||
|
import com.ankurm.tutorials.junit.extendwith.ext.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
|
import org.junit.jupiter.api.extension.*;
|
||||||
|
import org.junit.jupiter.api.io.*;
|
||||||
|
|
||||||
|
@ExtendWith(FirstExtension.class)
|
||||||
|
@ExtendWith(SecondExtension.class)
|
||||||
|
public class StackedFixture {
|
||||||
|
@Test
|
||||||
|
void test() {
|
||||||
|
EventLog.add(" test");
|
||||||
|
}
|
||||||
|
}
|
||||||
+21
@@ -0,0 +1,21 @@
|
|||||||
|
package com.ankurm.tutorials.junit.extendwith.fixtures;
|
||||||
|
|
||||||
|
import com.ankurm.tutorials.junit.extendwith.ext.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
|
import org.junit.jupiter.api.extension.*;
|
||||||
|
import org.junit.jupiter.api.io.*;
|
||||||
|
|
||||||
|
@ExtendWith(TimingExtension.class)
|
||||||
|
public class TimingFixture {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void fast() {
|
||||||
|
EventLog.add(" test fast");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void slow() throws InterruptedException {
|
||||||
|
Thread.sleep(30);
|
||||||
|
EventLog.add(" test slow (slept 30 ms)");
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
@@ -0,0 +1 @@
|
|||||||
|
com.ankurm.tutorials.junit.extendwith.ext.AutoRegisteredExtension
|
||||||
Reference in New Issue
Block a user