11

如果使用 JMock 编写带有模拟的 Java 单元测试,我们应该使用

Mockery context = new Mockery()

或者

Mockery context = new JUnit4Mockery()

两者有什么区别,我们什么时候应该使用哪个?

4

3 回答 3

9

@Rhys 不是替换调用的JUnit4Mockery需要,而是(与 结合)。创建常规.assertIsSatisfiedJMock.class@RunWithassertIsSatisfiedMockery

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)而不是错误

于 2010-06-07T07:37:09.633 回答
1

将 JMock 与 JUnit 4 一起使用时,您可以通过利用 JMock 测试运行程序来避免一些样板代码。当你这样做时,你必须使用 JUnit4Mockery 而不是常规的 Mockery。

以下是构建 JUnit 4 测试的方式:

@RunWith(JMock.class)
public void SomeTest() {
  Mockery context = new JUnit4Mockery();

}

主要优点是无需assertIsSatisfied在每次测试中调用,每次测试后都会自动调用。

于 2010-05-17T09:26:49.370 回答
0

更好的是,根据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();
     }
 }
于 2012-04-19T14:20:07.973 回答