'Failed to load ApplicationContext with OAuth2 resource server issuer URI when running @WebMvcTest

My Spring Boot application defines an OAuth2 resource server like this in the application.yml:

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: ${AUTH_SERVER_METADATA_URL:http://localhost:8080/auth/realms/demo}

This works fine when actually running the application.

When, however, running tests with@WebMvcTest and MockMvc to test a @RestController class, then the test fails with the following error:

java.lang.IllegalStateException: Failed to load ApplicationContext
...
...
...
I/O error on GET request for "http://localhost:8080/auth/realms/demo/.well-known/openid-configuration": Connection refused (Connection refused); nested exception is java.net.ConnectException: Connection refused (Connection refused)

The message is pretty clear in its root cause, but I don't know how I could "mock" the connection for sliced tests without spinning up a real Keycloak or WireMock server.

Running the same test with my development Keycloak server running in the background works fine.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source