Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 36 ยท Testing and Deployment

Mocks, Test Profiles and Test Resources

Replace beans with @InjectMock and alternatives, change configuration per test class with QuarkusTestProfile, start fakes with test resources and use the in-memory connector.

Integration-style tests are valuable, but some collaborators should not be real in a test: the payment gateway that charges cards, a mail server, a clock. Quarkus offers several tools to replace them, and a few more to change configuration for one group of tests. This lesson covers @InjectMock, alternative beans, QuarkusTestProfile, test resources and the in-memory messaging connector.

You should know the basics from testing with @QuarkusTest. Quarkus itself cannot run here, so the framework code is read-only and the TryIts rebuild the ideas with plain Java (a dynamic proxy for the mock, a merged configuration map for the profile).

Mocking a bean with @InjectMock

Add the Mockito integration:

XML
<dependency>
  <groupId>io.quarkus</groupId>
  <artifactId>quarkus-junit5-mockito</artifactId>
  <scope>test</scope>
</dependency>

Then replace a bean for the duration of one test:

Java
@QuarkusTest
class CheckoutResourceTest {

    @InjectMock PaymentGateway gateway;          // replaces the real bean in the whole app

    @Test
    void failedPaymentGives402() {
        Mockito.when(gateway.charge(Mockito.anyLong(), Mockito.anyString()))
               .thenReturn(PaymentResult.declined("insufficient funds"));

        given().body("{\"orderId\":1}").contentType("application/json")
          .when().post("/checkout")
          .then().statusCode(402);

        Mockito.verify(gateway).charge(1000L, "EUR");
    }
}

Facts that save debugging time:

  • The mocked type must be a normal-scoped bean such as @ApplicationScoped or @RequestScoped, because Quarkus swaps the proxy delegate. A @Singleton bean cannot be mocked this way; make it @ApplicationScoped or use @InjectMock(convertScopes = true).
  • The mock is reset after each test method; stubbing in one test does not leak into the next.
  • @InjectSpy wraps the real bean so you can verify calls and stub only some methods.
  • QuarkusMock.installMockForType(mock, Type.class) does the same programmatically, useful in @BeforeAll.
Java Stand-in: a mock built with a dynamic proxy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Alternatives: a fake bean for all tests

When many tests need the same fake (a clock fixed at one instant, a mail sender that stores messages), write an alternative in src/test/java:

Java
import io.quarkus.test.Mock;
import jakarta.enterprise.context.ApplicationScoped;

@Mock                                   // = @Alternative + @Priority(1) + @Dependent
@ApplicationScoped
class FakeMailer implements Mailer {
    final List<String> sent = new ArrayList<>();
    public void send(String to, String text) { sent.add(to + ": " + text); }
}

@Mock is a stereotype that makes the bean win over the real implementation whenever it is on the test classpath. It applies to every test in the module, so use per-test @InjectMock for specific behavior and an alternative for stable fakes. The CDI side is explained in the chapter on dependency injection.

Test profiles: change configuration per test class

By default the whole suite shares one application. When one group of tests needs different configuration, or different enabled alternatives, declare a test profile. Quarkus restarts the application once for each distinct profile:

Java
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import java.util.Map;
import java.util.Set;

public class FeatureFlagOnProfile implements QuarkusTestProfile {

    @Override
    public Map<String, String> getConfigOverrides() {
        return Map.of("shop.feature.new-checkout", "true");
    }

    @Override
    public Set<Class<?>> getEnabledAlternatives() {
        return Set.of(FakeMailer.class);
    }

    @Override
    public String getConfigProfile() {
        return "test";                   // keep the standard %test values
    }
}

@QuarkusTest
@TestProfile(FeatureFlagOnProfile.class)
class NewCheckoutTest { /* tests run with the flag turned on */ }

Because every distinct profile needs a restart, keep the number of profiles small, and group tests by profile. Test profiles also accept tags() so you can run only some profiles via -Dquarkus.test.profile.tags=....

Java Stand-in: merged configuration and one start per profile

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Test resources: start fakes and containers

A test resource is a class with start() and stop() that runs before the application and can return configuration. It is the tool for infrastructure that has no Dev Service, for example a WireMock server that plays a third-party API:

Java
public class ExchangeRateApiResource implements QuarkusTestResourceLifecycleManager {

    private WireMockServer server;

    @Override
    public Map<String, String> start() {
        server = new WireMockServer(options().dynamicPort());
        server.start();
        server.stubFor(get("/rates/EUR").willReturn(okJson("{\"USD\":1.1}")));
        return Map.of("exchange-api.url", server.baseUrl());    // injected as config
    }

    @Override
    public void stop() { server.stop(); }
}

@QuarkusTest
@WithTestResource(ExchangeRateApiResource.class)
class ConversionTest { ... }

(@WithTestResource is the current name; older Quarkus versions use @QuarkusTestResource.) The returned map overrides configuration, so the app talks to the fake URL without any code change. This pairs well with config sources: production reads the real URL from the environment and tests read the fake from the resource.

Messaging in tests: the in-memory connector

For reactive messaging, replace Kafka channels with in-memory ones so tests need no broker:

Java
public class InMemoryMessagingResource implements QuarkusTestResourceLifecycleManager {
    public Map<String, String> start() {
        Map<String, String> env = new HashMap<>();
        env.putAll(InMemoryConnector.switchIncomingChannelsToInMemory("orders"));
        env.putAll(InMemoryConnector.switchOutgoingChannelsToInMemory("invoices"));
        return env;
    }
    public void stop() { InMemoryConnector.clear(); }
}

@QuarkusTest
@WithTestResource(InMemoryMessagingResource.class)
class OrderPipelineTest {
    @Inject @Any InMemoryConnector connector;

    @Test
    void orderBecomesInvoice() {
        connector.source("orders").send(new Order(1, 10_000));
        await().untilAsserted(() ->
            assertEquals(1, connector.sink("invoices").received().size()));
    }
}

source("orders").send(...) plays the role of the broker delivering a message, and sink("invoices").received() lists what the application published.

Security in tests

With quarkus-test-security, @TestSecurity(user = "alice", roles = "admin") on a test or class pretends a user is logged in, so you can test secured endpoints without an identity provider. See security.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does @InjectMock do in a @QuarkusTest?

    The mock stands in for the bean everywhere it is injected, and is reset after each test.
  2. 2. When does Quarkus restart the application between test classes?

    Each distinct profile and resource set needs its own application start, so keep their number low.
  3. 3. What is a QuarkusTestResourceLifecycleManager for?

    Its start() can start infrastructure and return properties that are applied to the application configuration.
  4. 4. Which bean scope is required for @InjectMock by default?

    Normal-scoped beans are accessed through a client proxy whose delegate Quarkus can swap for the mock.

Summary

  • @InjectMock and @InjectSpy replace or wrap beans per test; @Mock alternatives give stable fakes.
  • QuarkusTestProfile changes configuration and alternatives for a group of tests, at the cost of an application restart.
  • Test resources start fakes and containers and feed configuration to the app.
  • The in-memory connector tests messaging without a broker; @TestSecurity fakes a login.

Next: Health, Metrics and Tracing