Search code examples
junitmockingjmock

When should we use Mockery vs JUnit4Mockery?


If writing a Java unit test with mocking using JMock, should we use

Mockery context = new Mockery()

or

Mockery context = new JUnit4Mockery()

What is the difference between the two, and when should we use which?


Solution

  • @Rhys It's not the JUnit4Mockery that replaces the need to call assertIsSatisfied, its the JMock.class (combined with the @RunWith). You wont need to call assertIsSatisfied when you create a regular Mockery.

    The JUnit4Mockery translates errors.

    By default, expectation exceptions are reported in Junit as ExpectationError, so for example, using

    Mockery context = new Mockery();
    

    you'll get

    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?
    

    and using,

    Mockery context = new JUnit4Mockery();
    

    you'll get

    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!
    

    The JUnit4Mockery converted the ExpectationError to an java.lang.AssertionError which JUnit deals with. Net result is that it'll show up in your JUnit report as an failure (using JUnit4Mockery) rather than an error.