JMockを使用してモックを使用してJavaユニットテストを作成する場合、
Mockery context = new Mockery()
また
Mockery context = new JUnit4Mockery()
2つの違いは何ですか?いつどちらを使用する必要がありますか?
@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 を使用して) 失敗として表示されます。
JUnit 4でJMockを使用する場合、JMockテストランナーを利用することで、ボイラープレートコードを回避できます。これを行うときは、通常のMockeryの代わりにJUnit4Mockeryを使用する必要があります。
JUnit4テストを構成する方法は次のとおりです。
@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();
}
}