【问题标题】:Mocked rest template exchange method returning null模拟休息模板交换方法返回 null
【发布时间】:2021-06-20 07:37:14
【问题描述】:

我正在尝试从休息模板模拟交换呼叫,但由于某种原因,我从呼叫中得到空响应,而不是我在测试中指定的响应实体。注意 - 在我的服务接口上添加 injectMocks 之前,其余模板试图进行实际调用,当我添加它时,它会进行模拟调用但结果为空。

@ActiveProfiles("unit-test")
@RunWith(SpringJUnit4ClassRunner.class)
@Category({ UnitTests.class })
@SpringBootTest@Import({PropertiesTestConfiguration.class})
public class MyTest {

    @Mock
    OAuth2RestTemplate serviceRestTemplate;

    @Autowired
    @InjectMocks
    ServiceInterface serviceInterface;
    
    @Test
    public void getServiceResponse_Success() {

        ResponseEntity<String> mockResponseEntity = new ResponseEntity<String>(mockResponseBody, HttpStatus.OK);

        String url = "https://unit_test_/XXX";
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);

        Mockito.when(serviceRestTemplate.exchange(    Matchers.anyObject(),     Matchers.any(HttpMethod.class),    Matchers.<HttpEntity> any(),     Matchers.<Class<String>> any()) ).thenReturn(mockResponseEntity);

        ServiceInterface.getClaimByClaimId(XXX);
    }

}

在我正在测试的方法中,返回 null

responseEntity = serviceRestTemplate.exchange(uriBuilder.toUriString(),
        method, requestEntity, String.class);

【问题讨论】:

    标签: java spring unit-testing mocking mockito


    【解决方案1】:

    如果您使用hamcrest 匹配器,我会推荐使用isisA 方法来匹配值或实例,这篇文章详细解释了core matchers

     Mockito.when(serviceRestTemplate.exchange(is(instanceOf(String.class)),     
                           is(HttpMethod.GET),    
                           is(HttpEntity.class),  
                           isA(String.class)))
                          .thenReturn(mockResponseEntity);
    

    【讨论】:

      猜你喜欢
      • 2020-03-08
      • 1970-01-01
      • 2011-09-30
      • 2019-08-30
      • 2018-12-20
      • 2020-01-21
      • 1970-01-01
      • 2017-02-18
      相关资源
      最近更新 更多