Часто достаточно создать объекты, равные ожидаемым значениям параметра:
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 для получения дополнительной информации