Nathan
Nathan

Reputation: 75

How to create an integration test for a Spring Boot controller using MockMvc and Spring Security filters?

I have a Spring Boot application that uses Spring Security to protect routes. Every time a user tries to access an endpoint, it goes through a security filter to authenticate the user. Now, I would like to create an integration test for a controller using MockMvc.

I've followed the official documentation, but I keep getting errors related to a custom bean from the WebSecurityConfig and its related dependencies. I've tried various combinations of annotations such as @SpringBootTest, @WebMvcTest, @ContextConfiguration, and @AutoConfigureMockMvc, but I can't seem to get it working.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
public class CsrfShowcaseTests {

@Autowired
private WebApplicationContext context;

private MockMvc mvc;

@Before
public void setup() {
    mvc = MockMvcBuilders
            .webAppContextSetup(context)
            .apply(springSecurity()) 1
            .build();
}

...

My goal is to have a controller integration test that tests only the controller layer, mocks dependencies, and uses a mock user (@WithMockUser) to pass the authentication filters.

Can anyone provide guidance on how to set up an integration test that meets these requirements?

Upvotes: 0

Views: 1322

Answers (1)

Ayush
Ayush

Reputation: 21

spring-security-test dependency provides good support for mocking users for integration tests..

You can use


@WithAnonymousUser or @WithMockUser 

Apart from this, to run the integration test you can :

  • Either use (this will enable complete context and you can mock the service layer using @MockBean):
@SpringBootTest
@AutoConfigureMockMvc(addFilters = false)
  • Or use can try using below setup :
@ExtendWith(SpringExtension.class)
@WebMvcTest(YourController.class)
@AutoConfigureMockMvc(addFilters = false)
@ImportAutoConfiguration(classes = {SecurityConfig.class})

Hope this helps..

Upvotes: 1

Related Questions