繁体   English   中英

使用@WebMvcTest 和 Mockito BDDMockito 测试 SpringBoot RestController

[英]Testing SpringBoot RestController using @WebMvcTest and Mockito BDDMockito

我对测试很陌生,最近我遇到了一些奇怪的事情,或者对于初学者来说可能并不奇怪。

SpringBoot版本:2.2.4.RELEASE
Mockito 核心:3.1.0

用例:使用@WebMvcTest 切片、MockBean、MockMvc 和 BDDMockito 进行 RestController 测试:

@WebMvcTest(Controller.class)
@AutoConfigureMockMvc(addFilters = false)
public class ControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private Service service;

    @Test
    @DisplayName("Some meaningful name")
    public void getXXXShouldBeSuccessful() throws Exception {
        ...
        //NOTE: I know creating objectDto here is useless, but i would like to understand 
        //why it doesn't work when it is passed in the method
        //ObjectDto objectDto = new ObjectDto();
        //objectDto.someSetter(id);
        ...
        given(service.methodName((ObjectDto) any(Object.class))).willReturn(true);   // This works
        //given(service.methodName(objectDto)).willReturn(true);                     //This doesn't work

        this.mockMvc.perform(post(some endpoint)...

还有我的 controller:

    @PostMapping(value = "/{id}")
    public ResponseEntity<JsonResponse> someMethod(
            @PathVariable String id,
            @Valid @RequestBody ObjectDto objectDto) {

        objectDto.someSetter(id);

        if(service.methodName(objectDto)) // <============ Returns false
        //Expected true, but if(service.methodName(objectDto)) is false when testing, 
        //although both objectDto(in my test, and here in the 
        //controller, has the same exact property values)

我通过使用(ObjectDto) any(Object.class)找到了解决方案,但最好理解为什么//given(service.methodName(objectDto)).willReturn(true); 不起作用。

是不是因为我是mocking服务方法,Mockito不关心object在方法中传递了什么?

注 1:objectDTO 只是一个 POJO。
注意 2:如果将 objectDTO 替换为Map ,它就可以工作!!!

试试这个:

when(service.methodName(any(ObjectDto.class)).thenReturn(true);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM