RestTemplate模拟抛出NullPointerException [英] RestTemplate Mock throws NullPointerException

查看:954
本文介绍了RestTemplate模拟抛出NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个rest模板,可以在服务类中的方法中进行调用,如下所示:

I have a rest template that makes a call in a method in a service class like so:

public CustomerResponse someMethod() {
CustomerResponse response = restTemplate.exchange(url, HttpMethod.GET, null,  CustomerRes.class).getBody();
return response;
}

尝试在测试类中模拟restTemplate时,它会在调用模拟restTemplate的行上不断抛出NullPointerException:

When trying to mock the restTemplate in my test class, it keeps throwing a NullPointerException on the line where the mock restTemplate is called:

public void checkResponseIsNotNull() {
CustomerResponse customerResponseMock = mock(CustomerResponse.class);
when(restTemplate.exchange(url, HttpMethod.GET, null, CustomerResponse.class).getBody()).thenReturn(customerResponseMock);
CustomerResponse cr = service.someMethod();
Assert.assertNotNull(cr);
}

为什么会抛出NullPointer?我之前已经嘲笑过RestTemplate,只是没有getBody()方法,这导致人们相信它会导致空指针.

Why is NullPointer being thrown? I have mocked a RestTemplate before, just without the getBody() method which leads be to believe its that which is causing the null pointer.

推荐答案

您应该再添加一个模拟级别:

You should add one more level of mocking:

CustomerResponse customerResponseMock = mock(CustomerResponse.class);
ResponseEntity reMock = mock(ResponseEntity.class);

when(reMock.getBody()).thenReturn(customerResponseMock);
when(restTemplate.exchange(url, HttpMethod.GET, null, CustomerResponse.class)).thenReturn(reMock);

CustomerResponse cr = service.someMethod();

最初,您只设置了ResponseEntity,而RestTemplate仍保留默认设置..因此,在调用exchange时返回null.

Originally you were setting-up the ResponseEntity only and the RestTemplate still remained with the defaults.. thus returning null when exchange has been called.

这篇关于RestTemplate模拟抛出NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆