简体   繁体   中英

Unit test using class with RestTemplate injected with java and spring boot

I'm running unit testing with a class that has the injected RestTemplate and only when I run the tests does RestTemplate get null after consuming the API I'm consuming.

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);
  }
}

Test 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();
    }
}

It looks like your test does not create a RestTemplate object because there is no code that processes the annotation @Mock . There are different ways for creating the mock. Eg you can init the mock in the init method.

@Override
public void init() {
    MockitoAnnotations.initMocks(this);
    receitaWsIntegration = new ReceitaWsIntegrationImpl(restTemplate);
}

For more options have a look at the Mockito's Javadoc .

Frankly speaking I do not see anything in findByCnpj() that requires its own unit-test. I don't think you need to test RestTemplate.getForEntity() method since it was tested many times by Spring developers (and testers). And there is no additional logic in findByCnpj()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM