【发布时间】:2016-02-03 15:31:08
【问题描述】:
如果使用 JMock 编写带有模拟的 Java 单元测试,我们应该使用
Mockery context = new Mockery()
或
Mockery context = new JUnit4Mockery()
这两者有什么区别,什么时候用哪个?
【问题讨论】:
如果使用 JMock 编写带有模拟的 Java 单元测试,我们应该使用
Mockery context = new Mockery()
或
Mockery context = new JUnit4Mockery()
这两者有什么区别,什么时候用哪个?
【问题讨论】:
@Rhys 不是JUnit4Mockery 取代了调用assertIsSatisfied 的需要,而是JMock.class(与@RunWith 结合使用)。当你创建一个普通的Mockery 时,你不需要调用assertIsSatisfied。
JUnit4Mockery 翻译错误。
默认情况下,Junit 中的期望异常报告为ExpectationError,例如,使用
Mockery context = new Mockery();
你会得到
unexpected invocation: bar.bar()
no expectations specified: did you...
- forget to start an expectation with a cardinality clause?
- call a mocked method to specify the parameter of an expectation?
并使用,
Mockery context = new JUnit4Mockery();
你会得到
java.lang.AssertionError: unexpected invocation: bar.bar()
no expectations specified: did you...
- forget to start an expectation with a cardinality clause?
- call a mocked method to specify the parameter of an expectation?
what happened before this: nothing!
JUnit4Mockery 将 ExpectationError 转换为 JUnit 处理的 java.lang.AssertionError。最终结果是它会在您的 JUnit 报告中显示为失败(使用 JUnit4Mockery)而不是错误。
【讨论】:
将 JMock 与 JUnit 4 一起使用时,您可以利用 JMock 测试运行程序来避免一些样板代码。当你这样做时,你必须使用 JUnit4Mockery 而不是常规的 Mockery。
以下是构建 JUnit 4 测试的方式:
@RunWith(JMock.class)
public void SomeTest() {
Mockery context = new JUnit4Mockery();
}
主要优点是每次测试都不需要调用assertIsSatisfied,每次测试后都会自动调用。
【讨论】:
更好的是,根据http://incubator.apache.org/isis/core/testsupport/apidocs/org/jmock/integration/junit4/JUnitRuleMockery.html 使用@Rule 并避免使用其他系统可能需要的@RunWith:
public class ATestWithSatisfiedExpectations {
@Rule
public final JUnitRuleMockery context = new JUnitRuleMockery();
private final Runnable runnable = context.mock(Runnable.class);
@Test
public void doesSatisfyExpectations() {
context.checking(new Expectations() {
{
oneOf(runnable).run();
}
});
runnable.run();
}
}
【讨论】: