[英]JUnit Mockito rest template Null Pointer Exception
我是 JUnit 和 Mockito 框架的新手。 在这里,我试图模拟 rest 模板并希望返回 HTTP 状态 200,但它仍然返回 null 值。 有人可以告诉我我的实现有什么问题,为什么它返回 null 值,而不是 HttpStatus OK。
Class MyDependencies{
@Autowired
RestTemplate template;
}
Class ABC extends MyDependencies{
void verify(){
try{
ResponseEntity<Object> response;
try{
response= template.postForEntity("localhost:....",obj,obj);
}catch(Exception e){
throws Exception.......
}
if(response.getStatusCodeValue()==200) // When reaches here, Exception is thrown
// becoz response is null
return new ResponseEntity<>(HttpStatus.OK);
else
throw Custom_Exception.....
}catch(Exception e){
throws Exception.....
}
}
}
测试
Class MyTesting{
@InjectMocks
ABC abc;
@Mock
RestTemplate template;
@BeforeEach
void setUp(){
abc=new ABC();
MockitoAnnotations.initMocks(this);
}
@Test
void testingIt(){
when(template.postForEntity(anyString(),any(),any())).thenReturn(new ResponseEntity<>(HttpStatus.OK));
Assertions.asserDoesNotThrow(()->abc.verify());
}
}
问题是我们从测试方法提供的匹配器与服务 class 中的实际 function 调用不匹配,因此未执行存根,响应为 Z37A6259CC0C1DAE299A7866489DFFBD0。
尝试像这样指定当存根
when(restTemplate.postForEntity(anyString(), any(), Mockito.<Class<String>>any()))
.thenReturn(new ResponseEntity<String>("{\"status\" : \"ok\"}", HttpStatus.OK));
在这种情况下,我将String
作为我通过 rest 模板发布的实体。 您可以在这里使用其他一些 class。
对此的服务 class 调用将如下所示
ResponseEntity<String> answer = template.postForEntity("/abc/1", entity, String.class);
此外,您的服务@InjectMocks
在您的测试中有@InjectMocks,因此您不需要此行
abc = new ABC();
MockitoAnnotations.initMocks(this)
已经在为你做这件事了。
@code_mechanic 是对的,问题在于测试方法提供的匹配器。
而不是下面的测试方法:
when(template.postForEntity(anyString(),any(),any())).thenReturn(new ResponseEntity<>(HttpStatus.OK));
试试这个,提供 url 而不是 anyString():
when(template.postForEntity(ArgumentMatchers.endsWith("/abc/1"),any(),any())).thenReturn(new ResponseEntity<>(HttpStatus.OK));
这样它会找出 URL 匹配存根,它对我有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.