java - 模拟休息模板

标签 java unit-testing mockito

 ResponseEntity<List<AgreementRecord>> myEntity = new 
 ResponseEntity<List<AgreementRecord>>(HttpStatus.ACCEPTED);

    when(restTemplate.exchange(
             ArgumentMatchers.anyString(),
             ArgumentMatchers.any(HttpMethod.class),
             ArgumentMatchers.<HttpEntity<?>>any(),
             ArgumentMatchers.<Class<?>>any())).thenReturn(myEntity);

其余模板从应用程序返回一个列表 Eclipse 抛出编译错误

OngoingStubbing 类型中的 thenReturn(ResponseEntity) 方法> 不适用于参数 (响应实体>)

休息模板

      ResponseEntity<List<AgreementRecord>> responseEntity = 
      restTemplate.exchange(smoUrl+ GET_AGREEMENT_RECORDS + customerId 
      ,HttpMethod.GET,null,new 
      ParameterizedTypeReference<List<AgreementRecord>>() {
       });
      responseEntity.getBody();

最佳答案

你可以做的一件事是使用 doReturn() 回避 Mockito 的编译时类型检查。 .

doReturn(myEntity)
    .when(restTemplate)
    .exchange(
        ArgumentMatchers.anyString(),
        ArgumentMatchers.any(HttpMethod.class)
        ArgumentMatchers.<HttpEntity<?>>any(),
        ArgumentMatchers.<Class<?>>any()));

这将返回 myEntity,而不进行编译时类型检查。如果您的类型错误,您一运行测试就会发现。

编辑:

@Test()
public void test() {
    class AgreementRecord {}

    ResponseEntity<List<AgreementRecord>> myEntity = new ResponseEntity<>(
        Arrays.asList(new AgreementRecord()), HttpStatus.ACCEPTED);
    doReturn(myEntity)
        .when(restTemplate)
        .exchange(
            anyString(),
            any(HttpMethod.class),
            any(),
            any(ParameterizedTypeReference.class));

    ResponseEntity<List<AgreementRecord>> responseEntity = restTemplate.exchange(
            "url", HttpMethod.GET, null, new ParameterizedTypeReference<List<AgreementRecord>>() {});

    List<AgreementRecord> body = responseEntity.getBody();

    assertTrue(responseEntity.getStatusCode().is2xxSuccessful());
    assertNotNull(body);
}

关于java - 模拟休息模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51263696/

相关文章:

unit-testing - 在 AngularJS 单元测试中模拟 $modal

unit-testing - CakePHP 3 : Set current time for unit testing

unit-testing - 如何为遗留的 Visual C++ 代码组织单元测试工具?

unit-testing - EclEmma、powermock 和 Java 7 问题

java - 模拟默认 SharedPreferences

java - 如何在 Java 中模拟单元测试的通用参数?

java - 在不同的类中运行 JButton ActionListener

JavaFX eclipse 配置 - openJDK 10

java - 如何将对象上下文传递给 Java 中的回调接口(interface)

java - 在 Java/Android 中维护一个可序列化的类