[英]How to write custom constraint using Jmock when the method to be mocked is having multiple argument
我在编写一些大型代码库的单元测试用例时遇到了困难,在这里我必须模拟很多类,以便可以轻松进行测试。 我在Jmock的API文档中发现,我可以使用的customeconstraint包含一个方法
eval(Object argo)
如果参数满足期望,则返回true。
但是我的方法被多个参数调用。 如何评估参数并确保调用该方法的参数正确。 提前致谢。
通常,创建等于预期参数值的对象就足够了:
context.checking(new Expectations() {{
allowing(calculator).add(1, 2);
will(returnValue(3));
DateTime loadTime = new DateTime(12);
DateTime fetchTime = new DateTime(14);
allowing(reloadPolicy).shouldReload(loadTime, fetchTime);
will(returnValue(false));
}});
JMock还提供了一些预定义的约束:
context.checking(new Expectations() {{
allowing(calculator).sqrt(with(lessThan(0));
will(throwException(new IllegalArgumentException());
}});
你也可以使用使用自定义匹配with
:
context.checking(new Expectations() {{
DateTime loadTime = new DateTime(12);
allowing(reloadPolicy).shouldReload(with(equal(loadTime)), with(timeGreaterThan(loadTime));
will(returnValue(false));
}});
在这里, timeGreaterThan
可以定义为:
public class TimeGreaterThanMatcher extends TypeSafeMatcher<DateTime> {
private DateTime minTime;
public TimeGreaterThanMatcher(DateTime minTime) {
this.minTime = minTime;
}
public boolean matchesSafely(DateTime d) {
return d != null && minTime.isBefore(d);
}
public StringBuffer describeTo(Description description) {
return description.appendText("a DateTime greater than ").appendValue(minTime);
}
public static Matcher<DateTime> timeGreaterThan(DateTime minTime) {
return new TimeGreaterThanMatcher(minTime);
}
}
有关更多信息,请参见JMock Cookbook 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.