11

JMockを使用してモックを使用してJavaユニットテストを作成する場合、

Mockery context = new Mockery()

また

Mockery context = new JUnit4Mockery()

2つの違いは何ですか?いつどちらを使用する必要がありますか?

4

3 に答える 3

9

@RhysJUnit4Mockeryを呼び出す必要性を置き換えるのは ではなくassertIsSatisfied、そのJMock.class( と組み合わせた@RunWith) です。assertIsSatisfied通常の を作成するときに呼び出す必要はありませんMockery

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 レポートには error ではなく (JUnit4Mockery を使用して) 失敗として表示されます。

于 2010-06-07T07:37:09.633 に答える
1

JUnit 4でJMockを使用する場合、JMockテストランナーを利用することで、ボイラープレートコードを回避できます。これを行うときは、通常のMockeryの代わりにJUnit4Mockeryを使用する必要があります。

JUnit4テストを構成する方法は次のとおりです。

@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 に答える