Home > Blockchain >  How to mock using Mockito?
How to mock using Mockito?

Time:01-14

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

How we will write a Junit testcase for this Controller using Mockito, using Mockito.when , then return.

CodePudding user response:

If you want to test your API, I would suggest Wiremock instead of Mockito.

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

If you want to write a unit test for your class by mocking attachmentService, you will need to do something like:

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

Check out this tutorial

CodePudding user response:

I'm assuming you're using 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());
  •  Tags:  
  • Related