在record和verify階段進行方法匹配時,
- 對于原始類型對象担猛,數(shù)值相同即可;
- 對于Object的子類丢氢,需要equals()返回true傅联;
- 對于數(shù)組,需要長度相等且每個對象equals()返回true;
除此之外疚察,如果不關心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);
}};
}
- 任何的基本類型都有對應的anyXyz貌嫡,anyString對應任意字符串比驻。
- any對應任意的對象该溯,在使用時需要進行顯式類型轉(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猾漫,則應該用 withNull() 方法点晴。
varargs
要么使用常規(guī)的參數(shù),要么使用any/with悯周,不能混合使用粒督。