【问题标题】:How to ignore interactions inside tested method如何忽略测试方法中的交互
【发布时间】:2020-03-09 15:04:23
【问题描述】:

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

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

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

【问题讨论】:

    标签: spring spring-boot junit junit5


    【解决方案1】:

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

    然后你只需要模拟那个单一的服务。

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

    【讨论】:

    • 你说得对,也许我举了愚蠢的例子,所以现在假设我们不是在谈论休息控制器,而是在谈论一些外观类。取而代之的是,我们在复杂的外观中使用了其他方法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-08
    • 2015-02-02
    • 1970-01-01
    • 2020-04-14
    • 1970-01-01
    • 2015-05-16
    • 1970-01-01
    相关资源
    最近更新 更多