6

I don't know why, but I have always written my JMock tests like this:

@Test
public void testMyThing() throws Exception {
    mockery.checking(new Expectations() {{
        oneOf(mockObj).foo();
    }});
    testObj.bar(); // calls mockObj.foo()
    mockery.assertIsSatisfied();
}

But when there are many tests, is it better to move assertIsSatisfied to the tear-down?

@After
public void tearDown() throws Exception {
    mockery.assertIsSatisfied();
}
skaffman
  • 398,947
  • 96
  • 818
  • 769
Paul McKenzie
  • 19,646
  • 25
  • 76
  • 120

2 Answers2

5

The recommended way to do this is to use the JMock runner. Annotate the class with

@RunWith(JMock.class)
public class TestClass {

This will call the assertion at the right place in the test lifecycle. Teardown isn't the right place as a failure might not be reported in correctly and might mess up other cleanup.

We also have a mockery rule in the repository that works with the new @Rule infrastructure.

Steve Freeman
  • 2,707
  • 19
  • 14
0

Yes, I tend to do it in teardown. It keeps the focus of the individual test methods on what they're actually testing, by removing the boilerplate out into the @After- it's critical to me that tests are as expressive and readable as possible.

In fact, I sometimes take it further than that, and use a JMockSupport base class that handles the Mockery for me (as well as providing convenience implementations of mock(...)). This is just a convenience, of course, and by no means a requirement like it was in JUnit 3.

skaffman
  • 398,947
  • 96
  • 818
  • 769
  • Please consider using the runner or the new rule implementation. If you use @After, the exception will not be thrown at the right time in the test lifecycle. – Steve Freeman Jun 06 '12 at 13:19