vendredi 30 novembre 2018

How to use @WebMvcTest and @WithUserDetails for integration test in Spring Boot

I'm struggling to get a test to run in Spring Boot 2.1.

I'm trying to use @WithUserDetails, as I have a custom UserDetails implementation.

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = SearchController.class)
public class SearchControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    @WithUserDetails("testuser")
    public void testPass_OpenAdvancedSearch() throws Exception {

        this.mockMvc.perform(get("/applications/advanced")).andExpect(status().isOk())
                .andExpect(content().string(containsString("</html>")));
    }

This is the UserDetailsService implementation:

@Configuration
public class TestConfig {

    @Bean
    public UserDetailsService userDetailsService() {
        return new TestUserDetails();
    }

}

However, this gives me a

No qualifying bean of type 'org.springframework.security.core.userdetails.UserDetailsService' available

To try and solve this, I add the below to my test class:

@Import( TestConfig.class)

...however this fails with:

IllegalStateException: The @PropertyMapping annotation @WebMvcTest cannot be used in combination with the @Component annotation @Configuration

I'm not sure what I'm doing wrong; the Boot documentation for @WebMvcTest here does suggest using @Import to add in additional beans as required. https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-autoconfigured-mvc-tests

If you need to register extra components, such as the Jackson Module, you can import additional configuration classes by using @Import on your test.

I tried removing the @Configuration annotation from the TestConfig class, but it doesn't make any difference.

Aucun commentaire:

Enregistrer un commentaire