Integrates jMock with JUnit 4.
To write a mock object test in JUnit 4, declare a field of type Mockery
that holds a JUnit4Mockery and annotate your test class with
@RunWith(JMock.class)
, as shown below. The Mockery will
be verified after the test has run and before the fixture is torn down.
import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.integration.junit4.JMock; import org.jmock.integration.junit4.JUnit4Mockery; import org.junit.Test; import org.junit.runner.RunWith; ... @RunWith(JMock.class) public class ExampleJUnit4MockObjectTest { Mockery context = new JUnit4Mockery(); ... @Test public void dispatchesEventToSessionsOtherThanThenSender() { ... context.checking(new Expectations() {{ ... }}); ... } }
Alternatively, from JUnit 4.7, you can use JMockContext
which
implements a JUnit Rule
to manage expectations and allowances, and to
assert the expectations after each test has run.
public class ATestWithSatisfiedExpectations { @Rule public final JMockContext context = new JMockContext(); private final Runnable runnable = context.mock(Runnable.class); @Test public void doesSatisfyExpectations() { context.checking(new Expectations() {{ oneOf (runnable).run(); }}); runnable.run(); } }