为什么我的 RestTemplate 的 Mockito 存根不起作用

why is my Mockito stub of RestTemplate not working

我是 运行 使用 Mockito 进行非常基本的单元测试

作为该测试的一部分,我有这些行

@Mock 
RestTemplate restTemplate;
...

@Before
target = new ServiceClass(params);
ReflectionTestUtils.setField(target, "url", "http://dummyendpoint");
...

@Test
byte[] expectedResponse = "any old byte array".getBytes();
given( restTemplate.postForObject( any (String.class), any( HttpEntity.class ), eq( byte[].class ), eq( param1 ), eq( param2 ), eq( param3 ) ) ).willReturn( expectedResponse );

byte[] response = target.performAction( creds, param1, param2, param3);

我意识到这有点空洞,但 a) 它现在符合我的目的 b) 我可以在此基础上进一步发展

所以在服务中我有一个正在测试的方法

@ResponseBody public byte[] performAction( SessionAuthenticationCredentials creds, String param1, String param2, String param3 ) {

    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders httpHeaders = getHttpHeaders( SessionAuthenticationCredentials );
    HttpEntity<Object> entity = new HttpEntity<Object>( httpHeaders );
    return restTemplate.postForObject( buildURL(), entity, byte[].class, param1, param2, param3 );
}

private String buildURL() {
    return url;
}

我发现当它在 performAction 方法中调用 postObject 方法时出现错误。我相信这是因为我的存根没有被调用,因为我得到的所有错误都是 post 试图实际使用 url 的结果(如果它是有效的 url 然后 "I/O error on POST request for...",如果是废话那么"java.lang.IllegalArgumentException: URI is not absolute".

谁能指出为什么我的存根被忽略了?也许我误解了任何 () 的用法?

在您的测试中,您正在创建 RestTemplate 的模拟并对其设置一些期望,但在您的服务中,您正在创建 RestTemplate 的新实例。因此,您在测试中设定的任何期望都将被忽略。

解决:

  • 在服务中使用 RestTemplate 字段。这是安全的。参见 Is RestTemplate thread safe?
  • 提供一种设置方法。服务中的构造函数参数看起来合适
  • 在您的测试中将该字段设置为模拟。