【问题标题】:How to mock "fluent" DataSourceHealthIndicator?如何模拟“流利”的 DataSourceHealthIndicator?
【发布时间】:2020-02-17 09:51:14
【问题描述】:

我正在使用Spring Boot 2.2.4.RELEASE

我的控制器中有这段代码,我使用“免费”DataSourceHealthIndicator 来检查数据库是否已关闭:

@Autowired 
private DataSourceHealthIndicator d;

//some code

if("DOWN".equals(d.getHealth(false).getStatus().getCode())) {
 // do something
} else {
 // proceed
}

现在,在我的切片测试中,我想模拟它(DataSourceHealthIndicator),但我有一个空指针,显然 getHealth() 没有返回 Health 对象,getStatus() 没有返回 Status对象...

@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:
状态 getHealth() 不能返回
getHealth() 应该返回 Health

【问题讨论】:

  • Mockito.when(d.getHealth(Mockito.any())).thenReturn(something);
  • 嗨@AlanHay,我试过了,但无法正常工作。
  • 抱歉,没有人能够帮助解决 但无法正常工作的错误描述
  • 嗨@AlanHay,看看编辑。另外,这与mockito deep stubs 有关,很遗憾您的解决方案不起作用。
  • 如果你使用得当的话,它显然工作得很好。

标签: spring-boot mockito spring-boot-actuator spring-boot-test


【解决方案1】:

DataSourceHealthIndicator 代码 转换为它自己的类。

这让我可以轻松地对 Controller 层进行切片测试,同时让我可以轻松地测试其他类,只需 MockitoExtension.class

SRP 和 KISS 原则在行动中。

【讨论】:

    猜你喜欢
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-05
    • 2011-09-17
    • 2016-01-13
    • 1970-01-01
    相关资源
    最近更新 更多