Reputation: 75
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
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 :
@SpringBootTest
@AutoConfigureMockMvc(addFilters = false)
@ExtendWith(SpringExtension.class)
@WebMvcTest(YourController.class)
@AutoConfigureMockMvc(addFilters = false)
@ImportAutoConfiguration(classes = {SecurityConfig.class})
Hope this helps..
Upvotes: 1