给定以下类:
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<String>
之前正确传递了。
我正在使用Mockito-Core 2.13.0
看起来匹配器不喜欢通过模拟方法而不是使用直接模拟此方法时使用的值。以下verify
工作得很好。
verify(logger).log(eq(info1), eq(info2), eq(VssNotificationStatus.ASSET_PREPARED), any());
因此,匹配者应使用真实值,而不是从模拟对象中获取它们。