使用Mockito直接在抽象类中测试Rest Client

时间:2019-04-02 18:39:59

标签: java spring

我有一个抽象类,其中有一个名为restInfo的方法,该方法使用restTemplate.exchange。我想直接使用Mockito测试方法,而无需创建另一个具体的类来测试此方法。但是,尝试这样做时,我得到了空指针异常。

当我在具体的类中使用相同的代码测试相同的其余客户端代码时,效果很好。

下面是抽象类:

    public abstract class classToBeTested{

            @Autowired
            private RestTemplate restTemplate;

            protected Response methodToBeTested(){

                String url = "https://example.com";

                HttpHeaders headers = new HttpHeaders();
                HttpEntity<String> entity = new HttpEntity<>(headers);

                ResponseEntity<ClaimsResponse> response = restTemplate.exchange(url, HttpMethod.GET, entity, Response.class);
                return response;
            }
      }


 @RunWith(MockitoJUnitRunner.class)
 public class Test{

    @Mock
    private RestTemplate restTemplate;


    @Test
    public void testMethod(){

        String url = "https://example.com";

        classToBeTested service = Mockito.mock(classToBeTested.class, Mockito.CALLS_REAL_METHODS);

        Response res = new Response();

        HttpHeaders headers = new HttpHeaders();
        HttpEntity<String> entity = new HttpEntity<>(headers);

        ResponseEntity<Response> response = new ResponseEntity<>(res, HttpStatus.OK);

        Mockito.when(restTemplate.exchange(url, HttpMethod.GET, entity, Response.class)).thenReturn(response);

        Response result = service.methodToBeTested();
        Assert.assertEquals("should be equal", res, result);
     }


}

该测试应该通过,但是我在下面的行中得到空指针异常:

    ResponseEntity<ClaimsResponse> response = restTemplate.exchange(url, HttpMethod.GET, entity, Response.class)

0 个答案:

没有答案