Don’t propagate exceptions in test fixtures

Been seeing this pattern a lot today. I’m working with integration tests, which have a lot of test fixtures around to do common tasks (such as inserting data into the database). These test fixtures propagate exceptions. In many cases, they simply declare that they throw java.lang.Exception. Ouch.


Exceptions coming from test fixtures are noisy; they mean that you clutter up your test code either with catches or unnecessary declarations of exceptions in your tests. Personally, the only time I’m willing to have an exception in a test method signature is when the production code-under-test throws the exception, AND it shouldn’t happen. Like this:

 /**
* Test something.
* @throws FooException - but won't.
*/
public void testDoesNotThrowFooException() throws FooException {
// ... set up test so that foo() can be thrown without errors.
test.foo();
}

And the only reason I am willing to accept that is because catching the exception makes for even more noise.

Test fixtures should catch exceptions and either fail (e.g. by calling junit.framework.Assert.fail()) or re-throw the exception as a RuntimeException. There is no reason why they should let the exception signature propagate out.

5 thoughts on “Don’t propagate exceptions in test fixtures

  1. I declare all my unit tests as “throws Throwable”, and never catch an exception in test code except in “try/fail/catch expected” idiom. Live happily ever after.

    Which sort of makes me curious – what value do you get from matching the throws clause of a test with the method under test?

  2. Readability. My test code is a good indication of what my production code that will use the code under test will be like. If I have exceptions being thrown all over the place, then that’s a problem.

    As said, I don’t have problems with the _production_ exceptions being on the test method. I have problems with the _test_ exceptions being on the test method, because it means I can’t see what production exceptions are coming out.

    I have the same problem with methods that regularly declare they throw some base Exception (be it java.lang.Exception or a project-level Exception). You’ve reduced the amount of information content in the code.

  3. Ideally you would do the setup of the “test” instance in the setUp() method of your test class, and therefore leaving your test method signature pristine …. ok, so maybe I like to fantasize.

Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s