我正在使用具有注入的RestTemplate的类来运行单元测试,并且只有在运行测试时,RestTemplate在使用我正在使用的API后才会为空。
class ReceitaWsIntegrationImpl implements ReceitaWsIntegration {
private static final String URL_RECEITA_WS_CNPJ
= "https://www.receitaws.com.br/v1/cnpj";
private final RestTemplate restTemplate;
@Override
public void findByCnpj(String cnpj) {
ResponseEntity<CnpjResource> forEntity = restTemplate.getForEntity(
URL_RECEITA_WS_CNPJ.concat("/").concat(cnpj), CnpjResource.class);
}
}
测试类:
public class ReceitaWsIntegrationImplTest extends TestSupport {
private static final String CNPJ = "27865757000102";
private static final String URL_RECEITA_WS_CNPJ = "https://www.receitaws.com.br/v1/cnpj/";
@Mock
private RestTemplate restTemplate;
private ReceitaWsIntegration receitaWsIntegration;
@Override
public void init() {
receitaWsIntegration = new ReceitaWsIntegrationImpl(restTemplate);
}
@Test
public void should_find_company_by_cnpj() {
receitaWsIntegration.findByCnpj(CNPJ);
InOrder inOrder = inOrder(restTemplate);
inOrder.verify(restTemplate, times(1))
.getForEntity(URL_RECEITA_WS_CNPJ.concat(CNPJ), CnpjResource.class);
inOrder.verifyNoMoreInteractions();
}
}
答案 0 :(得分:1)
您的测试似乎未创建RestTemplate
对象,因为没有代码可处理注释@Mock
。有多种创建模拟的方法。例如。您可以通过init
方法来初始化模拟。
@Override
public void init() {
MockitoAnnotations.initMocks(this);
receitaWsIntegration = new ReceitaWsIntegrationImpl(restTemplate);
}
有关更多选项,请查看Mockito's Javadoc。
答案 1 :(得分:0)
坦白说,我在findByCnpj()
中看不到任何需要自己进行单元测试的内容。我认为您不需要测试RestTemplate.getForEntity()
方法,因为它已经由Spring开发人员(和测试人员)测试了很多次。 findByCnpj()