JVM | Platform | Status |
---|---|---|
OpenJDK (Temurin) Current | Linux | |
OpenJDK (Temurin) LTS | Linux | |
OpenJDK (Temurin) Current | Windows | |
OpenJDK (Temurin) LTS | Windows |
A minimalist JUnit 5 extension to register AutoCloseable
resources that
will be destroyed after tests finish executing.
For whatever reason, JUnit 5 does not include any utility to register per-test resources and automatically have them cleaned up.
The zelador
package provides a tiny JUnit 5
extension that allows for registering AutoCloseable
objects that must be
closed after tests finish executing.
$ mvn clean verify
Annotate your test suite with @ExtendWith(ZeladorExtension.class)
. This
will allow tests to get access to an injected CloseableResourcesType
instance that can be used to register resources to be closed.
@ExtendWith(ZeladorExtension.class)
public final class ExampleTest
{
@Test
public void test0(
final CloseableResourcesType resources)
{
var output = resources.addPerTestResource(Files.newOutputStream(...));
...
}
@Test
public void test1(
final CloseableResourcesType resources)
{
var output = resources.addPerTestClassResource(Files.newOutputStream(...));
...
}
}
Resources added with addPerTestResource
will be closed after the individual
test has finished (as if it had been closed in an @AfterEach
method).
Resources added with addPerTestClassResource
will be closed after all tests
in the class have finished (as if it had been closed in an @AfterAll
method).
AutoCloseable
is a functional interface and, as such, it's trivial to pass
objects to the CloseableResourcesType
class that do not implement
AutoCloseable
by simply using a method reference:
class NotReallyCloseable {
public void finish() { ... }
}
NotReallyCloseable x;
resources.addPerTestResource(x::finish);