1

Consider the following test case:

@Test
public void testFooBar ()
        throws FooBadParameterException,
               FooInvalidStateException,
               BarUnmatchedException,
               BarDuplicatedException
{
    Foo foo = fooService.generateFoo();
    Bar bar = barService.generateBar();
    assertThat(foo.getId()).isEqualTo(bar.getId());
}

where FooBadParameterException, FooInvalidStateException, BarUnmatchedException, BarDuplicatedException are the checked exceptions that may be thrown by fooService.generateFoo() and barService.generateBar().

My question is: can I simplify the above test case into:

@Test
public void testFooBar ()
        throws Exception
{
    Foo foo = fooService.generateFoo();
    Bar bar = barService.generateBar();
    assertThat(foo.getId()).isEqualTo(bar.getId());
}

Although I didn't think of any reason not to do this, I want to ask if there is any hidden downside to do so.

Note: in In Java, is using throws Exception instead of throwing multiple specific exceptions good practice?, the accepted answer only cover the case for Spring MVC. My question focuses on test cases.

johnlinp
  • 853
  • 6
  • 22
  • For a test case, I think it would be fine. – markspace May 06 '20 at 05:23
  • When you use that method in another place, you'd want to categorically capture the exceptions. So throwing each one in that case is easy. Otherwise youd want to check which exception was fired in the catch clause and decide. For me thats the use case. Let's let an expert answer this. Just realized this is a test. I guess its ok in that case – Tharaka Devinda May 06 '20 at 05:25

1 Answers1

2

There's no strong reason against changing that into throws Exception. The first thing here is that you're talking about a test method, which means that no one is expected to call this method but the unit tests engine.

Therefore no one will need to handle these exceptions in any meaningful way (which would require knowing individual exception types for targeted handling). In the same line, no one will benefit from the documentation that the API would give implicitly.

I usually see the similarity between this and multiple exception types in the list "to be thrown" by main methods. There's no point other than silencing the compiler (assuming that those checked exceptions that need handling have been adequately handled in the method).

I find it better to keep my test methods free of these long throws clauses, so I normally turn them into throws Exception too.

ernest_k
  • 44,416
  • 5
  • 53
  • 99