我想验证对模拟的调用只会发生在某些预期的参数值上,而不会发生在其他任何事情上。
public interface ADependancy {
public void method(String parameter, String otherParameter);
}
public class Foo {
private ADependancy myHelper;
public Foo(ADependancy helper) {
this.myHelper = helper;
}
public void good() {
myHelper.method("expected","expected");
myHelper.method("expected","expected");
myHelper.method("expected","expected");
}
public void bad() {
myHelper.method("expected","expected");
myHelper.method("expected","UNexpected");
myHelper.method("expected","expected");
}
}
我试过这个:
public class FooTest extends TestCase {
private ADependancy mock =mock(ADependancy.class);;
private Foo foo = new Foo(mock);
@Test
public void testGood() {
foo.good();
validateOnlyCalledWithExpected();
}
@Test
public void testBad() {
foo.bad();
validateOnlyCalledWithExpected();
}
private void validateOnlyCalledWithExpected() {
verify(mock,atLeastOnce()).method(eq("expected"),eq("expected"));
verify(mock,never()).method(not(eq("expected")),not(eq("expected")));
}
}
期望 testBad 失败,但测试通过了。如果方法只接受一个参数,这将按预期工作。