| 1 |
<html> |
| 2 |
<body> |
| 3 |
<p>Integrates jMock with <a href="http://www.junit.org">JUnit 4</a>.</p> |
| 4 |
<p>To write a mock object test in JUnit 4, declare a field of type Mockery |
| 5 |
that holds a JUnit4Mockery and annotate your test class with |
| 6 |
<code>@RunWith(JMock.class)</code>, as shown below. The Mockery will |
| 7 |
be verified after the test has run and before the fixture is torn down. |
| 8 |
</p> |
| 9 |
|
| 10 |
<pre> |
| 11 |
import org.jmock.Expectations; |
| 12 |
import org.jmock.Mockery; |
| 13 |
import org.jmock.integration.junit4.JMock; |
| 14 |
import org.jmock.integration.junit4.JUnit4Mockery; |
| 15 |
import org.junit.Test; |
| 16 |
import org.junit.runner.RunWith; |
| 17 |
|
| 18 |
... |
| 19 |
|
| 20 |
<span>@</span>RunWith(JMock.class) |
| 21 |
public class ExampleJUnit4MockObjectTest { |
| 22 |
Mockery context = new JUnit4Mockery(); |
| 23 |
|
| 24 |
... |
| 25 |
|
| 26 |
<span>@</span>Test public void |
| 27 |
dispatchesEventToSessionsOtherThanThenSender() { |
| 28 |
... |
| 29 |
|
| 30 |
context.checking(new Expectations() {{ |
| 31 |
... |
| 32 |
}}); |
| 33 |
|
| 34 |
... |
| 35 |
} |
| 36 |
} |
| 37 |
</pre> |
| 38 |
|
| 39 |
<p>Alternatively, from JUnit 4.7, you can use <code>JMockContext</code> which |
| 40 |
implements a JUnit <code>Rule</code> to manage expectations and allowances, and to |
| 41 |
assert the expectations after each test has run.</p> |
| 42 |
|
| 43 |
<pre>public class ATestWithSatisfiedExpectations { |
| 44 |
\@Rule public final JMockContext context = new JMockContext(); |
| 45 |
private final Runnable runnable = context.mock(Runnable.class); |
| 46 |
|
| 47 |
\@Test |
| 48 |
public void doesSatisfyExpectations() { |
| 49 |
context.checking(new Expectations() {{ |
| 50 |
oneOf (runnable).run(); |
| 51 |
}}); |
| 52 |
|
| 53 |
runnable.run(); |
| 54 |
} |
| 55 |
}</pre> |
| 56 |
|
| 57 |
</body> |
| 58 |
</html> |