簡體   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