Mockito嘲笑restTemplate.postForEntity

Dax*_*rax 1 java testing unit-testing mocking mockito

我正在尝试模拟restTemplate.postForEntity方法,

实际的方法调用是:

URI myUri = new URI(myString);
HttpEntity<String> myEntity ...


String myResponse = restTemplate.postForEntity(myUri, myEntity, String.class);
Run Code Online (Sandbox Code Playgroud)

我的测试课是:

Mockito.when(restTemplate.postForEntity(any(URI.class), any(HttpEntity.class), eq(String.class))).thenReturn(response);
Run Code Online (Sandbox Code Playgroud)

这行不通;我尝试了其他几种排列方式,也都没有成功。任何建议表示赞赏,谢谢。

通过这种方式不起作用,我的意思是实际的方法被调用,而不是模拟的方法(因此不返回所需的结果,等等)。

小智 5

以下代码对我有用- when(mockRestTemplate.postForEntity(anyString(), any(), eq(String.class))).thenReturn(response);


ana*_*gam 5

这对我有用首先需要在测试类中模拟一个resttemplate

@Mock 
private RestTemplate mockRestTemplate;
Run Code Online (Sandbox Code Playgroud)

由于 ResponseEntity 返回一个对象,因此创建另一个方法返回包装在 ResponseEntity 中的预期响应

private ResponseEntity<Object> generateResponseEntityObject(String response, HttpStatus httpStatus){
    return new ResponseEntity<>(response, httpStatus);
}
Run Code Online (Sandbox Code Playgroud)

在您的测试用例中,您现在可以模拟预期响应,如下所示

String string = "result";
when(mockRestTemplate.postForEntity(anyString(), any(), any()))
        .thenReturn(generateResponseEntityObject(string, HttpStatus.OK));
Run Code Online (Sandbox Code Playgroud)