How to Mock REST API in unit testing?

前端 未结 2 615
挽巷
挽巷 2021-01-23 16:17

I am using RestTemplate exchange HttpMethod.POST method to POST to an endpoint. In my test file I am testing for success of the POST method. However wi

相关标签:
2条回答
  • 2021-01-23 16:28

    You are testing the logic inside DataTestRepo class, so you should not mock it. RestTemplate is a dependency inside DataTestRepo, so this is exactly what you need to mock. In general it should look like this inside your test:

    @InjectMocks
    private DataTestRepo DataTestRepo;
    @Mock
    RestTemplate restTemplate;
    

    Also, you will have to provide a return value for your mocked dependency, like this:

    Mockito.when(restTemplate.exchange(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any())).thenReturn(new ResponseEntity<>(yourExpectedDataHere, HttpStatus.OK));
    enter code here
    

    This is just a simple example. A good practice would be to check that the arguments passed to your mock equal to the expected ones. One way would be to replace ArgumentMatchers.any() with the real expected data. Another is to verify it separately, like this:

    Mockito.verify(restTemplate, Mockito.times(1)).exchange(ArgumentsMatchers.eq(yourExpectedDataHere), ArgumentsMatchers.eq(yourExpectedDataHere), ArgumentsMatchers.eq(yourExpectedDataHere), ArgumentsMatchers.eq(yourExpectedDataHere));
    
    0 讨论(0)
  • 2021-01-23 16:37

    This is a great read on this topic: https://reflectoring.io/spring-boot-web-controller-test/

    0 讨论(0)
提交回复
热议问题