Core Java

Proving There’s No Exception

How do you prove the existence of nothingness? Should you?

In some tests I’ve written, especially around either validation, or around creating an empty object, what I really want to write is something like:

1
2
assertThat( ... call some code ... )
   .doesntThrow();

You could reasonably write something like this. It would be the obverse of the assertThatThisThrowsException type of assertions that you’ll find kicking around.

If the thing your calling returns something, you might not bother. You could just as easily call the code and assert a result, safe in the knowledge that if the code DID throw an exception, then you’re testing for that by trying to reach the assertion for the result. The test will fail with an unexpected exception.

A question to ask, then is do we assert this didn’t explode? or just rely on the test not to end in failure as our assertion?

An Opinion

While writing assertThatThisThrows is better than the old school method of telling the test, before calling the code under test, that ending the test in the right sort of exception is a pass… which is as mad as it sounds, and messes up the order of prepare, act, assert, I don’t think you should do that for this case.

I think it’s ok to call a function as the way of proving it doesn’t throw. That’s the assumption of all tests. An unexpected error is test failure.

The problem is that without an assertion in a test, the test looks incomplete.

To solve this, I’d make the test name answer the question where’s the assertion?

E.g.

01
02
03
04
05
06
07
08
09
10
@Test
void whenDataIsValid_noValidationError() {
   validate("Foo Bar");
}
 
@Test
void whenDataIsInvalid_validationError() {
   assertThatThrownBy(() -> validate(""))
     .isInstanceOf(NoContentException.class);
}

I think you can use the whole test suite to tell the story along with sensible naming, and perhaps a comment thrown in for people who don’t read things.

Published on Java Code Geeks with permission by Ashley Frieze, partner at our JCG program. See the original article here: Proving There’s No Exception

Opinions expressed by Java Code Geeks contributors are their own.

Ashley Frieze

Software developer, stand-up comedian, musician, writer, jolly big cheer-monkey, skeptical thinker, Doctor Who fan, lover of fine sounds
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Elena gillbert
4 years ago

Hi…
I’m Elrna gillbert.The exception that proves the rule” (sometimes “the exception proves the rule”) is a saying whose meaning is contested. … In this sense, the phrase does not mean that an exception demonstrates a rule to be true or to exist, but that it tests the rule, thereby proving its value.

Back to top button