Spring boot “如何嘲笑”;流利的;数据源健康指示器?
我使用的是Spring boot “如何嘲笑”;流利的;数据源健康指示器?,spring-boot,mockito,spring-boot-actuator,spring-boot-test,Spring Boot,Mockito,Spring Boot Actuator,Spring Boot Test,我使用的是Spring Boot 2.2.4。请释放 我的控制器中有这段代码,我正在使用“free”datasourcehealthdicator检查数据库是否关闭: @Autowired private DataSourceHealthIndicator d; //some code if("DOWN".equals(d.getHealth(false).getStatus().getCode())) { // do something } else { // proceed }
Spring Boot 2.2.4。请释放
我的控制器中有这段代码,我正在使用“free”datasourcehealthdicator
检查数据库是否关闭:
@Autowired
private DataSourceHealthIndicator d;
//some code
if("DOWN".equals(d.getHealth(false).getStatus().getCode())) {
// do something
} else {
// proceed
}
现在,在我的切片测试中,我想模拟它(DataSourceHealthIndicator
),但我有一个空指针,因为显然getHealth()没有返回健康对象,getStatus()没有返回状态对象
@WebMvcTest
//some code
@MockBean
private DataSourceHealthIndicator d;
//some code
given(this.d.getHealth(anyBoolean()).getStatus().getCode()).willReturn("UP");
我怎样才能开始嘲笑它呢?
我试过这个:
given(this.d.getHealth(anyBoolean())).willReturn(Health.up().build());
given(this.d.getHealth(anyBoolean()).getStatus()).willReturn(Status.UP);
given(this.d.getHealth(anyBoolean()).getStatus().getCode()).willReturn("UP");
但它在第二条声明中失败了:
org.mockito.exceptions.misusing.ErrorTypeOfReturnValue:
状态
无法由getHealth()返回
getHealth()应返回运行状况
我将DataSourceHealthIndicator代码转换为自己的类
这使我能够轻松地对控制器层进行切片测试,同时也使我能够轻松地测试另一个类,只需使用MockitoExtension.class
SRP&KISS原则起作用。Mockito.when(d.getHealth(Mockito.any())。然后返回(某物)
Hi@AlanHay,我尝试过,但无法使其工作。很抱歉,没有人能够帮助进行错误描述,但无法使其工作Hi@AlanHay,请查看编辑。此外,这与mockito deep stubs
有关,不幸的是,您的解决方案不起作用。如果您正确地使用它,它显然工作得非常好。