【发布时间】: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