【发布时间】:2021-06-30 11:09:55
【问题描述】:
我是 JUnit 和 Mockito 框架的新手。在这里,我试图模拟其余模板并希望返回 200 的 HTTP 状态,但它仍然返回空值。有人能告诉我我的实现有什么问题吗?为什么它返回一个空值,而不是 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());
}
}
【问题讨论】:
-
您使用的是什么版本的 spring-boot 和 junit?
-
@code_mechanic Junit 5 & Spring 5.2.8
-
您是否使用
MockitoExtension类在您的测试类中指定了@ExtendWith注释? -
我没用,我在用 MockitoAnnotations.init(this)
-
无法复制,也无法从系统访问堆栈溢出。它非常安全......所以我只是提出了一个粗略的实现......我在两天前开始学习 JUnit 并且对很多东西感到困惑......
标签: java spring-boot junit mockito