Skip to content

io7m-com/zelador

Repository files navigation

zelador

Maven Central Maven Central (snapshot) Codecov Java Version

com.io7m.zelador

JVM Platform Status
OpenJDK (Temurin) Current Linux Build (OpenJDK (Temurin) Current, Linux)
OpenJDK (Temurin) LTS Linux Build (OpenJDK (Temurin) LTS, Linux)
OpenJDK (Temurin) Current Windows Build (OpenJDK (Temurin) Current, Windows)
OpenJDK (Temurin) LTS Windows Build (OpenJDK (Temurin) LTS, Windows)

zelador

A minimalist JUnit 5 extension to register AutoCloseable resources that will be destroyed after tests finish executing.

Features

  • Written in pure Java 21.
  • OSGi ready.
  • JPMS ready.
  • ISC license.
  • High-coverage automated test suite.

Motivation

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.

Building

$ mvn clean verify

Usage

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);