Suppose I have a method named foo which, for certain set of input values, is expected to complete successfully and return a result, and for some other set of values, is expected to throw a certain exception. This method requires some things to have set up before it can be tested.
Given these conditions, is it better to club success and failure tests in one test, or should I maintain these cases in separate test methods?
In other words, which of the following two approaches is preferable?
Approach 1:
@Test
public void testFoo() {
setUpThings();
// testing success case
assertEquals(foo(s), y);
// testing failure case
try {
foo(f);
fail("Expected an exception.")
} catch (FooException ex) {
}
}
Approach 2:
@Test
public void testFooSuccess() {
setUpThings();
assertEquals(foo(s), y);
}
@Test
public void testFooFailure() {
setUpThings();
try {
foo(f);
fail("Expected an exception.")
} catch (FooException ex) {
}
}
Best you go for approach #2.
Why:
Well when an asserts fails the rest of the method is not evaluated…
so by putting the tests in 2 separate methods you are sure to at least execute both tests.. failure or not.
Not only should a unit test focus on one specific unit, it should focus on one specific behaviour of that unit. Testing multiple behaviours at once only muddies the water.
Take the time to separate each behaviour into its own unit test.