In Java, what are the downsides of Unit test methods having 'throws Exception' clauses on them? #3508
-
In Java, what are the downsides of unit test methods having My usual practice is to write a JUnit 5 test like this: void testSomething_aScenarioThatThrowsException() {
Assertions.assertDoesNotThrow( () -> {
doSomeSetup_mightThrowJsonProcessingException();
IOException thrown = Assertions.assertThrows(IOException.class, () -> {
classUnderTest.doSomething();
});
assertEquals(thrown.getMessage(), "Whatver");
)};
} BUT other developers I work with want to put Other developers want to just put How do I convince my fellow developers to use my method. Is the way I do it better or not better? My point of view is that if you don't do it my way, the exceptions might not report out the same in the test reporting, but I can't prove that unless I build a Gradle/JUnit5 POC to prove it. Maybe I am wrong? Even the JUnit 5 devs are using the bad pattern, IMHO. So, maybe I am wrong? NOTE: I did write an example project where I tried to prove this hypothesis, but it's not super clear. I can say that the try-catch method, if a dev is not careful, does leave a dev open to making a unit test mistake WHERE the test does NOT clearly report the correct error when the test fails, but instead reports only an assertion message. This seems to be true, based on my research repo below: |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
To the best of my knowledge, there is no downside attached to using There is a slight difference in that a test failure caused by an |
Beta Was this translation helpful? Give feedback.
To the best of my knowledge, there is no downside attached to using
throws Exception
on a test method. JUnit will handle any Throwable thrown by the test method as a test failure. The only exception might beOutOfMemoryError
, but this error is also not caught byassertDoesNotThrow
. So in general, I would say usingthrows Exception
is completely fine and probably preferable since it is less noisy.There is a slight difference in that a test failure caused by an
AssertionFailedError
(which is used byAssertions
) might look a bit different from other exceptions. For example IntelliJ will visualize assertion errors in yellow, but other Throwables in red. You can use this to distinguish tests …