首页 > 解决方案 > 如何忽略测试方法中的交互

问题描述

所以我有复杂的休息控制器,我想忽略实现,只关注授权方面。

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

有什么模式可以清理这个烂摊子吗?

标签: springspring-bootjunitjunit5

解决方案


似乎更像是一个设计问题。控制器应尽可能薄。您的控制器应该委托给执行所有必要业务逻辑的单个服务。该服务将引用执行该逻辑所需的其他服务。

然后,您只需要模拟该单一服务。

https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/mock/mockito/MockBean.html

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

推荐阅读