有没有使用 JMock制作漂亮模拟的最佳方法?
例如:
public interface Dependency {
void someSetUp();
void interactionUnderTest();
void someCleaningAfterWork();
}
public class CUT {
private Dependency dependency;
public void methodUnderTest() {
dependency.someSetUp();
dependency.interactionUnderTest();
dependency.someCleaningAfterWork();
}
public void setDepencency(Dependency dependency) {
this.dependency = dependency;
}
}
对于 Mockito,解决方案很简单:
@Test
public void mockitoExample() throws Exception {
Dependency dependency = mock(Dependency.class);
classUnderTest.setDepencency(dependency);
classUnderTest.methodUnderTest();
verify(dependency).interactionUnderTest();
}
但是对于 JMock,我只找到了这个解决方案:
@Test
public void jMockExample() throws Exception {
JUnit4Mockery ctx = new JUnit4Mockery();
final Dependency dependency = ctx.mock(Dependency.class);
classUnderTest.setDepencency(dependency);
ctx.checking(new Expectations() {{
allowing(dependency).someSetUp();
one(dependency).interactionUnderTest();
allowing(dependency).someCleaningAfterWork();
}});
classUnderTest.methodUnderTest();
}
问题出在以下几行:
allowing(dependency).someSetUp();
and
allowing(dependency).someCleaningAfterWork();
如果 methodUnderTest 发生变化,例如通过从 Dependency 调用另一个方法,我将不得不手动修改测试以防使用 JMock。有没有办法避免呢?
PS对不起我的英语