Mocking APIs in Pure JUnit 5 (No Spring Needed)

Learn how to use StableMock with plain JUnit 5 tests. Mock external APIs without loading the full Spring context for faster, lighter integration tests.

While StableMock is famous for its seamless Spring Boot integration, it is built on top of the standard JUnit 5 Extension Model.

This means you can use it for lightweight integration tests where you don't want to pay the performance cost of starting the full Spring ApplicationContext.

Why Use Pure JUnit 5?

  • Performance: Tests run in milliseconds instead of seconds.
  • Simplicity: Test HTTP clients, parsers, or utility classes in isolation.
  • Flexibility: Works with any HTTP client (Java 11 HttpClient, OkHttp, Retrofit, etc.).

How to Configure It

The setup is identical to Spring Boot, but you remove the @SpringBootTest annotation. StableMock will verify it's running in a "pure" environment and adapt its behavior.

Accessing the Mock URL

Since there is no Spring Property Registry to auto-update, StableMock provides two ways to access the running WireMock server:

  1. Parameter Injection: Add an int port parameter to your test method.
  2. System Property: Read System.getProperty("stablemock.baseUrl").

Complete Example

Here is a full example using Java's native HttpClient.

@U(urls = { "https://jsonplaceholder.typicode.com" })
class PureJUnitTest {

    @Test
    void testWithInjectedPort(int port) {
        // 1. Build the base URL dynamically
        String baseUrl = "http://localhost:" + port;

        // 2. Create your HTTP client
        HttpClient client = HttpClient.newHttpClient();

        // 3. Point the request to the mock server
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(baseUrl + "/users/1"))
                .GET()
                .build();

        // 4. Execute and verify
        HttpResponse<String> response = client.send(request, BodyHandlers.ofString());

        assertEquals(200, response.statusCode());
        assertTrue(response.body().contains("\"id\": 1"));
    }

    @Test
    void testWithSystemProperty() {
        // Alternative: Use System Properties
        String baseUrl = System.getProperty("stablemock.baseUrl");
        assertNotNull(baseUrl);
    }
}

💡 Code Example: View the source at PureJUnitTest.java in the official repo.

System Properties Reference

StableMock exposes the following properties during execution, which you can use in any test setup:

Property Key Description
stablemock.baseUrl The base URL of the WireMock server (e.g., http://localhost:8081)
stablemock.port The integer port number (e.g., 8081)

Next: Explore GraphQL Mocking strategies.

Stop Rewriting Mocks By Hand, Son

Record once. Test offline forever.

Join developers who've made the switch. Free forever. No credit card required.

🌾 MIT License | 🚀 Open Source | 💯 Free Forever