Is it possible to test specific Spring REST endpoint security and avoid bootstrapping database connection?

Viewed 23

We have a couple of Spring tests that call a secured controller endpoints. Our goal is to assure that absence of particular user roles will result into HTTP 403 status. Our issue is that execution of those tests also bootstraps DB connection which we don't actually need. I've already tried countless number of all kind of annotations and manual configurations to avoid initialization of DB connection but so far without luck. Can you please share example how to do that? We use Spring Boot 2.7.

1 Answers

Yes, you can use @WebMvcTest, take a look at the docs. In summary, using @WebMvcTest will only bootstrap the Spring MVC components and avoid loading other application's layers. This annotation also automatically configures Spring Security for you, therefore you can test authentication/authorization rules.

Example:

@WebMvcTest(UserVehicleController.class)
class MyControllerTests {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private UserVehicleService userVehicleService;

    @Test
    @WithMockUser(roles = "ADMIN")
    void testAdminSuccess() throws Exception {
        given(this.userVehicleService.getVehicleDetails("sboot"))
            .willReturn(new VehicleDetails("Honda", "Civic"));
        this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN))
            .andExpect(status().isOk())
            .andExpect(content().string("Honda Civic"));
    }

    @Test
    @WithMockUser(roles = "USER")
    void testUserForbidden() throws Exception {
        this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN))
            .andExpect(status().isForbidden());
    }

}
Related