spring - 如何忽略测试方法中的交互
问题描述
所以我有复杂的休息控制器,我想忽略实现,只关注授权方面。
@RestController
public class SettingsController {
private final Service1
private final Service2
private final Service3
private final Service4
@PreAuthorize("hasRole('ROLE_ADMIN')")
@GetMapping("settings")
ResponseEntity subgrups() {
//impl using a service1/service2/service3/service4
}
}
因为我只想测试授权,所以我正在寻找这样的测试:
@WebMvcTest(controllers = SettingsController.class)
public class SettingsControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
@WithMockUser(role="ADMIN")
public void whenSearchingForGroupAndHasAccessToPolicy() throws Exception {
mockMvc.perform(get("/settins"))
.andExpect(status().isOk());
}
}
但不幸的是,因为我有很多互动,我的测试看起来像
@WebMvcTest(controllers = SettingsController.class)
public class SettingsControllerTest {
//mock service1
//mock service2
//mock service3
//mock service4
@Autowired
private MockMvc mockMvc;
@Test
@WithMockUser(role="ADMIN")
public void whenSearchingForGroupAndHasAccessToPolicy() throws Exception {
//build some mock for service1
//mock interaction service1
//build some mock for service2
//mock interaction service2
//build some mock for service3
//mock interaction service3
//build some mock for service4
//mock interaction service4
mockMvc.perform(get("/settins"))
.andExpect(status().isOk());
}
}
有什么模式可以清理这个烂摊子吗?
解决方案
似乎更像是一个设计问题。控制器应尽可能薄。您的控制器应该委托给执行所有必要业务逻辑的单个服务。该服务将引用执行该逻辑所需的其他服务。
然后,您只需要模拟该单一服务。
@WebMvcTest(controllers = SettingsController.class)
@MockBean(classes = {SettingsService.class})
public class SettingsControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
@WithMockUser(role="ADMIN")
public void whenSearchingForGroupAndHasAccessToPolicy() throws Exception {
mockMvc.perform(get("/settins"))
.andExpect(status().isOk());
}
}
推荐阅读
- extjs - EXTJS 条形图垂直条未位于正确(中心)位置。怎么做?
- node.js - TypeError:无法读取 Nexmo API 中未定义的属性“发送”
- html - How to Vertical ion-item Scroll to Bottom and Top on Down and Up arrow icon button click in ionic 4?
- r - 根据 row.names 从时间戳中选择数据范围
- javascript - 如何使 if else 代码更好,React js
- python-3.x - 从此图像中删除线条
- entity-framework - 在实体框架迁移中添加值取决于其他列值的列
- printing - 通过 Internet 使用 CUPS 打印
- java - 如何使用 DynamicJasper 运行垂直报告(列作为值)?
- opengl-es - 绘制到纹理后的Opengl ES 2.0 glDeleteFramebuffers