R. Polito
R. Polito

Reputation: 544

Configuration Getting Ignored in Test

I try to test my spring app but encounter following problem: In "normal mode"(mvn spring-boot:run) the app starts as expected and adapterConfig gets set and is NOT NULL. When I start my testclass to test the MVC, adapterConfig does not get set. Spring ignores the whole config class.

test:

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = StudentController.class)
public class StudentControllerTests {
    @Autowired
    private MockMvc mockMvc;
    @MockBean
    private StudentService service;
    @MockBean
    private StudentRepository repository;
    @Test
    public void shouldReturnABC() throws Exception{
        MvcResult result = this.mockMvc.perform(get("/students/abc")).andReturn();
    }
}

controller:

@RestController
@RequestMapping("/students")
@PermitAll
public class StudentController {
    @Autowired
    StudentService studentService;
    //get
    @GetMapping("/abc")
    public String abc (){
        return "abc";
    }

config:

@Configuration
public class SpringBootKeycloakConfigResolver implements KeycloakConfigResolver {
    private KeycloakDeployment keycloakDeployment;
    private AdapterConfig adapterConfig;
    @Autowired
    public SpringBootKeycloakConfigResolver(AdapterConfig adapterConfig) {
        this.adapterConfig = adapterConfig;
    }
    @Override
    public KeycloakDeployment resolve(OIDCHttpFacade.Request request) {
        if (keycloakDeployment != null) {
            return keycloakDeployment;
        }
        keycloakDeployment = KeycloakDeploymentBuilder.build(adapterConfig);
        return keycloakDeployment;
    }
}

adapterConfig is null when hitting the test but gets set & created when hitting it the normal way, any idea?

Upvotes: 2

Views: 1176

Answers (3)

denov
denov

Reputation: 12688

with spring boot 2.5 i had I had to import KeycloakAutoConfiguration into my test.

@WebMvcTest(value = ApplicationController.class, properties = "spring.profiles.active:test")
@Import(KeycloakAutoConfiguration.class)
public class WebLayerTest { 
        // ... test code ....
}

Upvotes: 0

Cyril G.
Cyril G.

Reputation: 2017

Using @WebMvcTest, the container will inject only components related to Spring MVC (@Controller, @ControllerAdvice, etc.) not the full configuration use @SpringBootTest with @AutoConfigureMockMvc instead.

Spring Boot Javadoc

Upvotes: 2

eidottermihi
eidottermihi

Reputation: 282

Keycloak's AutoConfiguration is not included by @WebMvcTest.

You could

  1. Include it manually via @Import(org.keycloak.adapters.springboot.KeycloakSpringBootConfiguration.class)
  2. Or use @SpringBootTest

Upvotes: 1

Related Questions