是否可以测试特定的SpringREST端点安全性并避免引导数据库连接



我们有几个Spring测试,它们调用安全的控制器端点。我们的目标是确保特定用户角色的缺失将导致HTTP403状态。我们的问题是,这些测试的执行也会引导我们实际上并不需要的DB连接。我已经尝试了无数种注释和手动配置来避免数据库连接的初始化,但到目前为止还没有成功。你能分享一下如何做到这一点的例子吗?我们使用Spring Boot 2.7。

是的,您可以使用@WebMvcTest,看看文档。总之,使用@WebMvcTest只会引导SpringMVC组件,避免加载其他应用程序的层。此注释还自动为您配置Spring Security,因此您可以测试身份验证/授权规则。

示例:

@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());
}
}

最新更新