【问题标题】:Mocking method taking a Supplier<String> method not working采用 Supplier<String> 方法的模拟方法不起作用
【发布时间】:2018-06-01 23:41:48
【问题描述】:

给定以下类:

class Logger {
  public void log(String someInfo,
                  String someOtherInfo,
                  VssNotificationStatus status,
                  Supplier<String> message)
  {}
}

class Asset {
  private String name;
  private String alias;

  Asset(String name, String alias) {
    this.name = name;
    this.alias = alias;
  }

  public String getName() {
    return name;
  }

  public String getAlias() {
    return alias;
  }
}

class ClassUnderTest {
  private Logger logger;

  ClassUnderTest(Logger logger) {
    this.logger = logger;
  }

  public void methodUnderTest(Asset asset) {
    logger.log(asset.getName(), asset.getAlias(), VssNotificationStatus.ASSET_PREPARED, () -> String.format("%s is running", "methodUnderTest"));
  }
}

以及下面的测试代码:

@RunWith(MockitoJUnitRunner.class)
public class TestA {
  private ClassUnderTest clazz;
  @Mock
  private Logger logger;

  @Before
  public void setup() {
    clazz = new ClassUnderTest(logger);
  }

  @Test
  public void test() {
    // given
    String info1 = "info1";
    String info2 = "info2";
    Asset asset = mock(Asset.class);
    given(asset.getName()).willReturn(info1);
    given(asset.getAlias()).willReturn(info2);

    // when
    clazz.methodUnderTest(asset);

    // then
    verify(logger).log(eq(asset.getName()), eq(asset.getAlias()), eq(VssNotificationStatus.ASSET_PREPARED), any());
  }
}

verify 行失败

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
0 matchers expected, 1 recorded

我尝试使用isA(Supplier.class),在any方法中指定Supplier.class,但还是同样的错误。感觉 Mockito 没有正确模拟这种方法。

在将最后一个参数从简单的String 参数重构为Supplier&lt;String&gt; 之前,那些失败的测试正常通过。

我正在使用 mockito-core 2.13.0

【问题讨论】:

  • 以上代码对我来说没有任何问题
  • 您提到的异常仅在以下情况下发生:1. Logger 是最终类或 2. 您正在调用的对象(logger)不是模拟对象或未正确初始化为模拟对象
  • 有趣...我的简单示例也可以正常工作。所以这绝对是我真正的测试中的东西......
  • 如上所述。它可能发生在上述情况之一。抱歉,答案很混乱。我删除了那个。重新检查你的真实测试
  • 查看我更新的问题(重现错误)和我的答案。

标签: java unit-testing functional-programming mockito


【解决方案1】:

看起来 Matchers 不喜欢你传入一个模拟方法而不是使用你直接模拟这个方法时使用的值。以下verify 工作正常。

verify(logger).log(eq(info1), eq(info2), eq(VssNotificationStatus.ASSET_PREPARED), any());

所以匹配器应该使用真实值,而不是从模拟对象中获取它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-29
    • 1970-01-01
    • 2020-12-20
    • 2016-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-22
    相关资源
    最近更新 更多