在record和verify階段進(jìn)行方法匹配時,
- 對于原始類型對象,數(shù)值相同即可;
- 對于Object的子類,需要equals()返回true;
- 對于數(shù)組,需要長度相等且每個對象equals()返回true;
除此之外,如果不關(guān)心replay時的具體參數(shù),可以使用anyXyz或者withXyz(...)方法。
使用"any"
@Test
public void someTestMethod(@Mocked final DependencyAbc abc)
{
final DataItem item = new DataItem(...);
new Expectations() {{
abc.voidMethod(anyString, (List<?>) any);
}};
new UnitUnderTest().doSomething(item);
new Verifications() {{
abc.anotherVoidMethod(anyLong);
}};
}
- 任何的基本類型都有對應(yīng)的anyXyz,anyString對應(yīng)任意字符串。
- any對應(yīng)任意的對象,在使用時需要進(jìn)行顯式類型轉(zhuǎn)換: (CastClass) any
- mockit.Invocations類中有可以使用所有anyXyz
- 使用時參數(shù)位置需要一致
使用"with"
any的限制太寬松,with可以選擇特定的子集。
@Test
public void someTestMethod(@Mocked final DependencyAbc abc) {
final DataItem item = new DataItem(...);
new Expectations() {{
abc.voidMethod("str", (List<?>) withNotNull());
abc.stringReturningMethod(withSameInstance(item), withSubstring("xyz"));
}};
new UnitUnderTest().doSomething(item);
new Verifications() {{
abc.anotherVoidMethod(withAny(1L));
}};
}
也可以自定義with方法。
使用"null"
null可以與任何對象匹配,好處是避免類型轉(zhuǎn)換,但是需要有一個any或者with
。
@Test
public void TestMethod(@Mocked final Dependency mock) {
new StrictExpectations() {{
//測試會失敗,因為沒有any或者with
mock.mockMethod(2, null);
//測試通過
mock.mockMethod(anyInt, null);
}};
mock.mockMethod(new Integer(2), "hello world");
}
如何需要的是null,則應(yīng)該用 withNull() 方法。
varargs
要么使用常規(guī)的參數(shù),要么使用any/with,不能混合使用。