Testing Java SPI Providers With Mock Implementations
Java’s Service Provider Interface (SPI) allows an application to discover implementations at runtime without depending directly on their concrete classes. The pattern is common in JDBC drivers, logging frameworks, compression libraries, plugin systems, security providers and application-specific extension points. ServiceLoader finds providers through configuration files or Java module declarations, then creates them when the application asks for a service.
That runtime indirection is useful in production, but it can make automated tests harder to control. A test may accidentally load a real database driver, contact an external system, depend on the machine’s classpath, or pass simply because a provider is installed in the developer’s environment. A small mock provider gives the test a deterministic implementation while preserving the same discovery mechanism used in production.
For teams working across Sydney, Melbourne, Brisbane and remote locations, this distinction matters. A provider that appears on a developer laptop may be absent from a clean CI agent, and AEST/AEDT differences can expose timing assumptions in asynchronous tests. Treating SPI discovery as a testable boundary helps keep builds reliable during an afternoon release push—or, in local terms, before the arvo gets away from everyone.
How Java SPI Discovery Works
An SPI starts with a service interface or abstract class. The application calls ServiceLoader.load() with that service type, and Java searches for provider declarations. In the classic classpath arrangement, the declaration is a UTF-8 file under META-INF/services, with a filename equal to the fully qualified service name.
public interface PaymentGateway {
PaymentResult charge(String customerId, BigDecimal amount);
}
A provider might look like this:
public final class BankPaymentGateway implements PaymentGateway {
public BankPaymentGateway() {
}
@Override
public PaymentResult charge(String customerId, BigDecimal amount) {
return PaymentResult.approved();
}
}
The matching resource is:
src/main/resources/META-INF/services/com.example.PaymentGateway
Its content is simply:
com.example.BankPaymentGateway
The application can then discover and use it:
PaymentGateway gateway = ServiceLoader.load(PaymentGateway.class)
.findFirst()
.orElseThrow(() -> new IllegalStateException("No gateway installed"));
Providers must generally have a public no-argument constructor when using the traditional SPI mechanism. Java modules provide another option: the service interface module declares uses, while the provider module declares provides ... with .... Tests that mix the module path and classpath need to account for both forms, since a resource file alone may not register a provider in a strongly modularised application.
Designing A Mock Provider
A mock SPI provider should behave like a real implementation from the caller’s point of view, while exposing enough state for assertions. It should not replace the discovery mechanism with direct construction. If the production code calls ServiceLoader, the test should register the fake provider and allow ServiceLoader to find it.
public final class RecordingPaymentGateway implements PaymentGateway {
private final List<ChargeRequest> requests = new ArrayList<>();
@Override
public PaymentResult charge(String customerId, BigDecimal amount) {
requests.add(new ChargeRequest(customerId, amount));
return PaymentResult.approved();
}
public List<ChargeRequest> requests() {
return List.copyOf(requests);
}
}
Place a test-only service declaration under src/test/resources:
META-INF/services/com.example.PaymentGateway
with this provider name:
com.example.RecordingPaymentGateway
A JUnit test can now exercise the application through the SPI boundary. If the service loader is created inside the production class, the test can assert the resulting behaviour rather than reaching into private implementation details. If the application needs several providers, the test resource can list several implementations, one per line, and the test can verify selection rules explicitly.
A useful fake provider also supports failure scenarios. It might throw a controlled exception, return a rejected result, delay completion, or record cancellation. For REST clients, an SPI-backed HTTP transport can return a known 429 or 503 response without calling an external endpoint. That is safer than relying on a live sandbox, particularly when Australian payment or banking integrations have rate limits and maintenance windows outside the team’s working hours.
Keep the mock small. A fake that reproduces the whole production provider often creates a second system to maintain. Its job is to make discovery deterministic and expose the interactions needed by the test, not to reimplement network protocols, persistence, authentication and retry policies.
Controlling Classpaths And Loaders
The most common SPI testing failure is a resource collision. A real provider may be available in src/main/resources, while a mock provider is available in src/test/resources. Both service files can be visible to the test runtime, and ServiceLoader may discover both. The result can depend on classpath order, which is fragile across Maven, Gradle, IDEs and CI runners.
A robust design gives the test an isolated classloader or an explicit provider selection policy. The following example loads providers from a dedicated test classloader:
URL[] urls = {
Paths.get("build/test-fixtures").toUri().toURL()
};
try (URLClassLoader loader =
new URLClassLoader(urls, PaymentGateway.class.getClassLoader())) {
ServiceLoader<PaymentGateway> services =
ServiceLoader.load(PaymentGateway.class, loader);
PaymentGateway gateway = services.findFirst()
.orElseThrow();
}
In a normal unit test, placing the fake service declaration in a separate test fixture module is often cleaner than manipulating URLs directly. Gradle source sets, Maven test fixtures, or a dedicated test JAR can isolate provider metadata and classes. This is especially useful when multiple test classes require different provider behaviours, such as a successful gateway, a timeout gateway and a malformed-response gateway.
ServiceLoader is lazy: provider constructors may not run until iteration begins. Tests should therefore trigger discovery deliberately with stream(), iterator() or findFirst(). Assertions that only inspect the ServiceLoader object do not prove that a provider can be instantiated.
Classloader identity also matters. A service interface loaded by one classloader is different from a class with the same name loaded by another. Plugin tests should load the service interface and provider in compatible classloader hierarchies, then close disposable URL classloaders to avoid leaks. This concern tends to appear first on long-running CI agents, including shared infrastructure used by distributed Australian teams.
Verifying Behaviour And Failure Paths
A useful SPI test suite checks three layers. The first confirms discovery: the expected provider is present, it can be instantiated, and its service declaration has the right fully qualified name. The second checks application behaviour when that provider is selected. The third checks what happens when discovery or provider execution fails.
@Test
void usesRecordingProviderThroughSpi() {
PaymentService service = new PaymentService();
PaymentResult result = service.pay("customer-42",
new BigDecimal("19.95"));
assertThat(result).isEqualTo(PaymentResult.approved());
}
For more direct discovery checks:
@Test
void discoversTheTestProvider() {
List<PaymentGateway> providers =
ServiceLoader.load(PaymentGateway.class)
.stream()
.map(ServiceLoader.Provider::get)
.toList();
assertThat(providers)
.hasAtLeastOneElementOfType(RecordingPaymentGateway.class);
}
Test missing providers by running with an empty service configuration or an isolated classloader. The expected outcome might be a clear application exception rather than a raw NoSuchElementException. Test malformed provider declarations too: a misspelled class, a provider without the required constructor, and a provider whose static initialisation fails should each produce an understandable diagnostic.
Provider ordering deserves an explicit test if the application uses the first discovered implementation. The Java SPI contract does not provide a general-purpose business priority mechanism. If selection matters, prefer a provider name, capability check, configuration property or a separate registry. A mock provider can then represent each candidate without making the test depend on incidental classpath order.
For asynchronous services, make the fake deterministic with CompletableFuture, virtual time or a controllable executor. Avoid Thread.sleep() when checking retries or timeouts. A provider that completes on demand makes failures reproducible across machines, from a developer workstation in Perth to a CI runner in an eastern-state data centre.
A Practical Test Matrix
Before adding tests, decide which boundary is under examination. A unit test for business rules may inject a PaymentGateway directly and does not need SPI at all. A discovery test should use ServiceLoader and test resources. An integration test can verify that the packaged JAR contains the service descriptor and that the application can load it after assembly.
| Scenario | Provider setup | Main assertion | Suitable test level |
|---|---|---|---|
| Successful discovery | Recording provider in test resources | Expected provider is instantiated | Unit or component |
| Provider interaction | Fake records requests | Correct arguments and call count | Unit |
| Rejected operation | Fake returns a declined result | Application maps the result correctly | Unit |
| Provider exception | Fake throws a controlled exception | Error handling and logging are correct | Unit |
| No provider | Empty or isolated classloader | Clear startup or runtime failure | Component |
| Bad declaration | Unknown class or invalid constructor | Diagnostic identifies configuration error | Component |
| Packaged application | Provider descriptor in built JAR | Provider loads from the artifact | Integration |
| Multiple providers | Several descriptors or modules | Selection rule is deterministic | Component |
Build tooling should inspect the packaged artifact, not just the source tree. A JAR can be missing META-INF/services because of an incorrect resources configuration, a shading plugin can merge service files incorrectly, or a module build can omit a provides declaration. An integration test that runs against the assembled artifact catches these errors before deployment.
The clearest architecture keeps provider selection near the application boundary. Pass the selected service into domain code, record the discovery decision in diagnostics, and make provider failures observable without exposing secrets. This is valuable when a production issue crosses regions or time zones: a team in Melbourne should be able to see which implementation loaded, while a team in Perth can reproduce the same selection locally.
Mock providers are most effective when they preserve the real extension point, isolate external effects and make unusual states easy to produce. The key lesson is simple: test both the provider’s behaviour and the mechanism that discovers it. A fake implementation in test resources, an intentional classloader strategy and a small set of failure-focused checks will make Java SPI integrations predictable across laptops, packaged builds and Australian CI environments.