Explain Codes LogoExplain Codes Logo

How to test that no exception is thrown?

java
assertions
junit
test-coverage
Anton ShumikhinbyAnton ShumikhinΒ·Oct 12, 2024
⚑TLDR
// Using a try-catch construct. This is like doing math with a hammer: try { targetMethod(); } catch (Exception e) { assert false : "Expected no surprises, but BOOM πŸ’₯: " + e; }

In JUnit tests, your method is a little angel if no exception is thrown:

@Test public void shouldNotThrowException() { targetMethod(); // Innocent until proven guilty! }

Feeling fancy with AssertJ? Here's a more fluent style:

import static org.assertj.core.api.Assertions.assertThatCode; @Test public void shouldNotThrowExceptionWithAssertJ() { assertThatCode(() -> targetMethod()).doesNotThrowAnyException(); // Swag by Fluent API University 🎩 }

Surefire ways to assert no exceptions

Expressing clear intention with assertDoesNotThrow

assertDoesNotThrow() gives your test readability a steroid shotπŸ’‰:

@Test public void testMethodWithoutException() { Assertions.assertDoesNotThrow(() -> targetMethod()); // "I've got 99 problems, but an exception ain't one!" 🎢 }

Keep test cases squat and muscular

Each test method should flex one single behavior. This keeps your test suite ripped and ready to fight off bugs πŸ’ͺ:

Break up is hard to do, thanks to assertAll():

@Test public void testMultipleAspects() { assertAll("Should not throw exceptions and yet change state like a chameleon 🦎", () -> Assertions.assertDoesNotThrow(() -> targetMethod()), () -> assertEquals(expectedState, actualState) ); }

Test a variety bag of inputs

Feed these to JUnit's Parameterized tests for thorough cross-examinations:

@ParameterizedTest @ValueSource(strings = {"input1", "input2", "input3"}) // "Eat this, and this, and this..." 🍎πŸ₯¦πŸ” public void testWithMultipleInputs(String input) { Assertions.assertDoesNotThrow(() -> targetMethod(input)); }

This effectively runs our assertDoesNotThrow() test with different meal courses.

Playing catch with specific exceptions

Catching Exception is like using a fishing net for a goldfishβ€”always be specific:

@Test(expected = SpecificException.class) public void testForSpecificException() { methodThatThrowsSpecificException(); // "Catch me if you can!" 🐠 }

Testing lower layers for peace of mind

Test the lower layers of your code like your life depends on it. Would you read Lord of the Rings starting from the middle?

Using JUnit Rules for a clean court

When exceptions pull a Mata Hari, @Rule dons the Judge's robe to rule them in or out across multiple tests.

Keeping tests neat and tidy

As Stitch says, "Test is family, family means no one gets left behind". Maintain yours like Lilo with JUnit and AssertJ.