如果使用JMock编写带有模拟的Java单元测试,我们是否应该使用
Mockery context = new Mockery()或
Mockery context = new JUnit4Mockery()这两者之间的区别是什么,我们应该在什么时候使用哪一个?
发布于 2010-06-07 15:37:10
@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。Net的结果是,它将在您的JUnit报告中显示为失败(使用JUnit4Mockery),而不是错误。
发布于 2010-05-17 17:26:49
在JUnit 4中使用JMock时,您可以利用JMock测试运行器来避免一些样板代码。在执行此操作时,必须使用JUnit4Mockery,而不是常规的Mockery。
下面是JUnit 4测试的结构:
@RunWith(JMock.class)
public void SomeTest() {
Mockery context = new JUnit4Mockery();
}它的主要优点是不需要在每次测试中调用assertIsSatisfied,它会在每次测试后自动调用。
发布于 2012-04-19 22:20:08
更好的是,根据规则使用@ http://incubator.apache.org/isis/core/testsupport/apidocs/org/jmock/integration/junit4/JUnitRuleMockery.html,并避免使用@Rule,因为您可能需要在其他系统中使用它:
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();
}
}https://stackoverflow.com/questions/2825280
复制相似问题