Reputation: 2491
I'm writing a Unit test for the behavior of a method, and want to try to reduce my code duplication - I'm about to double the test cases again, and the file is getting a bit hard to look at.
If anyone's really interested, the code is here (warning to the future - link may not be permanent).
Right now, I do the following, repeated several times in slightly different ways:
@Test
public void testAdd64OfMax64() {
// Set up container
TileEntityChest nmsinv = new TileEntityChest();
Inventory container = new CraftInventory(nmsinv);
// Call method
HashMap<Integer,ItemStack> leftover = container.addItem(new ItemStack(Foo, 64));
// Set up expected result
ItemStack[] expected = empty.clone();
expected[0] = new ItemStack(Foo, 64);
// Verify result
assertThat(container.getContents(), is(expected));
assertThat(leftover, is(Collections.EMPTY_MAP));
}
(Note: assertThat comes from org.hamcrest.Matchers
.)
I know that I can put the "Set up container" and cloning the empty array into a @Before method.
My question is, can I put the assertThat
method into an @After method and have the test still fail (when it should fail)?
Upvotes: 3
Views: 115
Reputation: 274878
No. The After
method should be used to release external resources after a test run. Also, note that it is guaranteed to run even if your Test
method throws an exception which may not be desirable in your case.
Also, think about the people who will have to maintain your code in the future. You are violating the PLA, by validating the results of your tests in the After
method. Nobody expects that!
It would be better if you created a helper method e.g. checkResults
which was called at the end of each of your Test
methods to validate your results.
Upvotes: 3