如何模拟 "fluent" DataSourceHealthIndicator?
How to mock "fluent" DataSourceHealthIndicator?
我正在使用 Spring Boot 2.2.4.RELEASE
。
我的 控制器中有这段代码 ,我正在使用 "free" DataSourceHealthIndicator
检查数据库是否已关闭:
@Autowired
private DataSourceHealthIndicator d;
//some code
if("DOWN".equals(d.getHealth(false).getStatus().getCode())) {
// do something
} else {
// proceed
}
现在,在我的切片测试中,我想模拟它(DataSourceHealthIndicator
),但我有一个空指针,因为显然 getHealth() 没有返回 Health 对象,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.WrongTypeOfReturnValue:
Status
cannot be returned by getHealth()
getHealth() should return Health
我将 DataSourceHealthIndicator 代码 转移到它自己的class。
这让我可以轻松地对控制器层进行切片测试,同时它也让我可以轻松地测试另一个 class,只需要 MockitoExtension.class
。
SRP 和 KISS 原则在行动。
我正在使用 Spring Boot 2.2.4.RELEASE
。
我的 控制器中有这段代码 ,我正在使用 "free" DataSourceHealthIndicator
检查数据库是否已关闭:
@Autowired
private DataSourceHealthIndicator d;
//some code
if("DOWN".equals(d.getHealth(false).getStatus().getCode())) {
// do something
} else {
// proceed
}
现在,在我的切片测试中,我想模拟它(DataSourceHealthIndicator
),但我有一个空指针,因为显然 getHealth() 没有返回 Health 对象,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.WrongTypeOfReturnValue:
Status cannot be returned by getHealth()
getHealth() should return Health
我将 DataSourceHealthIndicator 代码 转移到它自己的class。
这让我可以轻松地对控制器层进行切片测试,同时它也让我可以轻松地测试另一个 class,只需要 MockitoExtension.class
。
SRP 和 KISS 原则在行动。