【问题标题】:Not able to Mock Static method that returns boolean无法模拟返回布尔值的静态方法
【发布时间】:2021-12-31 07:38:24
【问题描述】:
try(MockedStatic<ValidatorUtil> theMock = Mockito.mockStatic(ValidatorUtil.class)) {
    Assertions.assertNotNull(theMock);
    theMock.when(() -> ValidatorUtil.isValid(configurator)).thenReturn(true);
    Assertions.assertTrue(ValidatorUtil.isValid(configurator));
}

我编写了以下内容来模拟一个名为 ValidatorUtil 的类,该类在测试中用于验证字符串,所以我写了 ValidatorUtil 应该总是返回 true,但它总是返回 false,它实际上结束了调用ValidatorUtilisValid 方法,返回结果为false。我已经尝试过所有匹配器,如Mockito.any()Mockito.any(Configurator.class),但没有运气。请帮忙

【问题讨论】:

  • 上面的代码是否失败(如果它是整个测试体)?如果您使用 Mockito.any() 匹配器,它会失败吗?你在 try 块中有你的测试吗?

标签: java spring spring-boot unit-testing mockito


【解决方案1】:
try(MockedStatic<ValidatorUtil> theMock = Mockito.mockStatic(ValidatorUtil.class)) {
    Assertions.assertNotNull(theMock);
    Mockito.when(theMock.isValid(configurator)).thenReturn(true);
    Assertions.assertTrue(ValidatorUtil.isValid(configurator));
}

不应该是这样的

【讨论】:

  • 实际上没有 MockedStatic 期望在 when() 中有一个函数参数,它可以使用我已经完成的 lambda 传递,然后在传递的函数上调用 apply,您显示的是标准 Mock 而不是 MockedStatic
  • theMock.when(ValidatorUtil::isValid).thenReturn(true);
  • 我们不能这样做,因为 isValid 方法需要一个参数,像这样你不能调用一个需要参数的方法
猜你喜欢
  • 1970-01-01
  • 2012-11-03
  • 1970-01-01
  • 2022-01-11
  • 2020-06-01
  • 2012-11-04
  • 2015-06-18
  • 1970-01-01
相关资源
最近更新 更多