【问题标题】:Having trouble to mock Rest Template postForEntity()无法模拟 Rest Template postForEntity()
【发布时间】:2021-05-13 15:32:57
【问题描述】:

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

实际的方法调用是:

final UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url).queryParam("string", "query string");

final HttpHeaders headers = new HttpHeaders();
      headers.add("Content-Type", "application/x-www-form-urlencoded");
final HttpEntity<String> entity = new HttpEntity<String>(headers);
ResponseEntity<String> response = null;
JSONObject responseObject;
response = restTemplate.postForEntity(builder.build().toUri(), entity, String.class);
responseObject = new JSONObject(response.getBody());

我的测试课是:

String response = "{" +
                "\"name\": \"john\"," +
                "\"id\": \"123\"" +
                "}";
when(mockRestTemplate.postForEntity(anyString(), any(), any())).thenReturn(ResponseEntity.ok().body(response));

即使我在模拟响应,我也无法取回响应并返回空值作为响应。 感谢任何帮助!

【问题讨论】:

  • 请展示您如何将模拟的 restTempate 注入到您的组件中
  • @Mock RestTemplate mockRestTemplate;
  • 这显示了你如何定义模拟,而不是你如何注入它。 (像 runner / extesnion 这样的测试类的任何相关注释也将很有用)
  • @Lesiak code@RunWith(SpringRunner.class) @SpringBootTest public class ABCServiceImplTest { @InjectMocks private ABCServiceImpl abcService; @Mock RestTemplate mockRestTemplate; } code

标签: java junit mockito resttemplate


【解决方案1】:

您在嘲笑 postForEntity 方法的错误重载。 检查RestTemplate javadoc

<T> ResponseEntity<T> postForEntity(String url, Object request, Class<T> responseType, Object... uriVariables)
<T> ResponseEntity<T> postForEntity(URI url, Object request, Class<T> responseType)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多