繁体   English   中英

如何使用 Mockito 进行模拟?

[英]How to mock using Mockito?

@GetMapping(path = {"/attachment/answer/{answerId}"})
    public APIResponse<List<AttachmentVM>> getAttachmentListForAnswer(@PathVariable("answerId") UUID answerId) {
        List<AttachmentBO> attachmentBOList = this.attachmentService.getAttachmentListForAnswer(answerId);
        List<AttachmentVM> noteVMList = super.mapList(attachmentBOList, AttachmentVM.class);
        return APIResponse.ok(noteVMList);
    }

我们将如何使用 Mockito 为这个 Controller 编写 Junit 测试用例,然后使用 Z4D1142CA816EAC93E33B383,然后返回 0.B7B53,

如果您想测试您的 API,我建议使用 Wiremock而不是 Mockito。

@Test
public void shouldGetEndpoint() {
  String path = "/endpoint";
  wiremock.stubFor(get(urlEqualTo(path))
          .willReturn(aResponse()
                  .withStatus(200))
  );
}

如果您想通过 mocking attachmentService为您的 class 编写单元测试,您需要执行以下操作:

List<AttachmentBO> providedList = new ArrayList<>();
MyService attachmentService = Mockito.mock(MyService.class);
when(attachmentService.getAttachmentListForAnswer(any())).thenReturn(providedList);

看看这个教程

我假设您使用的是 Springboot。

@Autowired private MockMvc mockMvc;
@MockBean private AttachmentService attachmentService;
    
@Test public void test() {
     List<AttachmentBO> attachmentBOList = new ArrayList<>();
     String answerId = "myId";         

     // mocking your service here by directly returning the list 
     // instead of executing the code of the service class
     Mockito.when(attachmentService.getAttachmentListForAnswer(answerId))
            .thenReturn(attachmentBOList);
     
     // calling the controller
     String url = "/attachment/answer/" + answerId;
     this.mockMvc.perform(MockMvcRequestBuilders.get(url))
                 .andExpect(MockMvcResultMatchers.status.isOk());

暂无
暂无

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

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