I d开发者_JS百科on'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();
}
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.
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.
精彩评论