RestTemplate 模拟给出 NullPointerException

T A*_*nna 3 mockito resttemplate spring-boot

我的服务类代码如下:

public class MyServiceImpl implements MegatillAccessService {
@Autowired
RestTemplate restTemplate;

@Value("${api.key}")
private String apiKey;

@Value("${customers.url}")
private String postUrl;

@Override
public String pushCustomerData(List<Customer> listOfcustomers, String storeId) throws MyServiceException {

Set<Customer> setOfCustomers = new HashSet<>(listOfcustomers);
    int noOfCustomersLoadedSuccessfully =0;

    MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
    headers.add("apiKey", apiKey);
    headers.add("Content-Type", "application/json");
    headers.add("storeId", storeId);
    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

    for(Customer customer: setOfCustomers){
        HttpEntity<Customer> request = new HttpEntity<Customer>(customer, headers);
        CustomerDataDto customerDataDto = null;
        try {
            customerDataDto = restTemplate.exchange(postUrl, HttpMethod.POST, request, CustomerDataDto.class).getBody();
        }
        catch (HttpClientErrorException ex) {
            if (ex.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
                log.error("The customers service is not available to load data: "+ ex.getResponseBodyAsString(), ex);
                throw new MyServiceException("The customers service is not available to load data",new RuntimeException(ex));
            }
            else{
                log.warn("Error for customer with alias: "+customer.getAlias() +" with message: "+ ex.getResponseBodyAsString(), ex);
                if(!ex.getResponseBodyAsString().contains("already found for this shop")){
                    throw new MyServiceException("An error occurred while calling the customers service with status code "+ex.getStatusCode(),new RuntimeException(ex));
                }
            }
        }
        catch(Exception e){
            throw new MyServiceException("An error occurred while calling the customers service: ",new RuntimeException(e));
        }

        if(null != customerDataDto) {
            noOfCustomersLoadedSuccessfully++;
            log.debug("--------Data posted successfully for: ---------"+customerDataDto.getAlias());
        }
    }
    String messageToReturn = "No. of unique customers from source: "+setOfCustomers.size()+". No. of customers loaded to destination without error: "+noOfCustomersLoadedSuccessfully;
    return messageToReturn;
}
}
Run Code Online (Sandbox Code Playgroud)

我的测试类如下:

@RunWith(MockitoJUnitRunner.class)
@SpringBootTest
public class MyServiceTest {

@InjectMocks
private MyService myService = new MyServiceImpl();

@Mock
RestTemplate restTemplate;

@Before
public void setUp() throws Exception
{
    MockitoAnnotations.initMocks(this);
    initliaizeModel();
    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
}

@Test
public void pushAllRecords(){

    Mockito.when(restTemplate.exchange(Matchers.anyString(), Matchers.any(HttpMethod.class), Matchers.<HttpEntity<?>> any(), Matchers.<Class<CustomerDataDto>> any()).getBody()).thenReturn(customerDataDto);

    /*Mockito.when(restTemplate.exchange(Mockito.anyString(),
            Mockito.<HttpMethod> eq(HttpMethod.POST),
            Matchers.<HttpEntity<?>> any(),
            Mockito.<Class<CustomerDataDto>> any()).getBody()).thenReturn(customerDataDto);*/

    String resultReturned = myService.pushCustomerData(customers,"1235");
    assertEquals(resultReturned, "No. of unique customers from source: 2. No. of customers loaded to destination without error: 2");
}

}
Run Code Online (Sandbox Code Playgroud)

在运行测试时,我在给出 Mockito.when 和 thenReturn 条件的行中收到 NullPointerException。我尝试了很多组合,但它仍然给 NPE。我什至无法访问方法调用。你能告诉我我哪里出错了吗?

mic*_*brz 7

你得到NullPointerException是因为你在你的Mockito.when. 你里面的代码when(较短的版本):

restTemplate.exchange(args).getBody()

您正在尝试模拟,getBody()但它被调用了exchange(args)。什么exchange(args)返回?Mockito 不知道它应该返回什么,并且您没有指定它,因此默认情况下它返回null.

这就是您获得 NPE 的原因。

要解决此问题,您可以逐步进行模拟,即。

ResponseEntity re = Mockito.when(exchange.getBody()).thenReturn(customerDataDto);
Mockito.when(restTemplate.exchange()).thenReturn(re);
Run Code Online (Sandbox Code Playgroud)

或者指定 mock 返回deep stubs,像这样(如果你想使用注释):

@Mock(answer = Answers.RETURNS_DEEP_STUBS)
RestTemplate restTemplate;
Run Code Online (Sandbox Code Playgroud)