【发布时间】:2021-06-24 21:31:52
【问题描述】:
我是 JUnit 和 Mockito 概念的新手,并试图弄清楚它是如何在 rest 模板调用中完成的。 考虑下面的粗略实现,
Class TheWrapper{
@Autowired
RestTemplate template;
}
Class Abc extends TheWrapper{
boolean validation(){
// .....
//carries out different validation operations
// .....
try{
ResponseEntity<Object> response= template.postForEntity("localhost:8080...",obj,Object.class);
if(response.getStatusCodeValue()==200) // Problem: throwing MyCustomException here,
// when test is runned
return true;
else
return false;
}catch(Exception e){
throws new MyCustomException(...);
}
}
现在我需要以这样一种方式编写单元测试,我必须模拟其余的模板调用和
检查状态码是否为200。
Class Testing{
@InjectMock
Abc obj;
@Mock
RestTemplate template;
@BeforeEach
void setup(){
obj=new Abc();
MockitoAnnotations.initMocks(this);
}
@Test
void testingIt(){
ResponseEntity<Object> response=new ResponseEntity<Object>(HttpStatus.OK);
when(template.postForEntity("local...",any(),any())).then(response)
Assertion.assertEquals(obj.validation(),true);
}
}
如果这不是实现的方式,请纠正我。
【问题讨论】:
标签: java spring-boot unit-testing junit mockito