Testing exceptions and timeouts
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite must refuse a quantity of 0, an unknown SKU or a negative price. If nothing tests those refusals, a bug there will reach a customer.
assertThrows returns the exception
assertThrows(ExpectedType.class, executable) runs the lambda and passes only if it throws an exception of that type or a subclass. It then returns the exception, so the test can check its message.
Bad input must be rejected, so the rejection needs a test too. Here Cart.add must refuse a quantity of 0.
Example 1 · How assertThrows works: a hand-rolled version
import java.math.BigDecimal;
public class AssertThrowsByHand { interface Executable { void execute() throws Throwable; }
static <T extends Throwable> T assertThrows(Class<T> expectedType, Executable code) { try { code.execute(); } catch (Throwable actual) { if (expectedType.isInstance(actual)) { return expectedType.cast(actual); // hand the exception back to the test } throw new AssertionError("Unexpected exception type thrown, expected: <" + expectedType.getName() + "> but was: <" + actual.getClass().getName() + ">"); } throw new AssertionError("Expected " + expectedType.getName() + " to be thrown, but nothing was thrown."); }
static void addToCart(String sku, BigDecimal price, int quantity) { if (quantity < 1) { throw new IllegalArgumentException("Quantity must be at least 1"); } }
public static void main(String[] args) { IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> addToCart("NB-A5", new BigDecimal("60.00"), 0)); System.out.println("thrown as expected: " + e.getMessage());
try { assertThrows(IllegalArgumentException.class, () -> addToCart("NB-A5", new BigDecimal("60.00"), 2)); } catch (AssertionError failure) { System.out.println("test fails: " + failure.getMessage()); }
try { assertThrows(IllegalArgumentException.class, () -> addToCart(null, null, 1 / 0)); } catch (AssertionError failure) { System.out.println("test fails: " + failure.getMessage()); } }}thrown as expected: Quantity must be at least 1 test fails: Expected java.lang.IllegalArgumentException to be thrown, but nothing was thrown. test fails: Unexpected exception type thrown, expected: <java.lang.IllegalArgumentException> but was: <java.lang.ArithmeticException>
What this code does
- The core of
assertThrowsis atryaround your lambda: return the exception if it has the expected type, fail if it has another type, and fail if nothing was thrown. The messages copy JUnit's wording. - Returning the exception is the useful part: the test can then check the message, which proves it failed for the right reason (quantity), not some other
IllegalArgumentException.
Example 2 · Error-path tests for the cart
Runs in: a Maven project with JUnit 5 (shoplite-api: src/test/java/com/shoplite/cart)
package com.shoplite.cart;
import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertThrows;
import java.math.BigDecimal;
import org.junit.jupiter.api.Test;
class CartErrorsTest {
private static final BigDecimal NOTEBOOK_PRICE = new BigDecimal("60.00");
@Test void aQuantityOfZeroIsRejected() { Cart cart = new Cart();
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> cart.add("NB-A5", NOTEBOOK_PRICE, 0));
assertEquals("Quantity must be at least 1", e.getMessage()); assertEquals(0, cart.itemCount()); // nothing was added }
@Test void removingAnUnknownSkuIsRejected() { Cart cart = new Cart(); cart.add("NB-A5", NOTEBOOK_PRICE, 1);
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> cart.remove("PEN-BLU"));
assertEquals("No line for PEN-BLU", e.getMessage()); }
@Test void theLinesCannotBeChangedFromOutside() { Cart cart = new Cart(); cart.add("NB-A5", NOTEBOOK_PRICE, 1);
assertThrows(UnsupportedOperationException.class, () -> cart.lines().clear()); }}[INFO] Running com.shoplite.cart.CartErrorsTest [INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.052 s -- in com.shoplite.cart.CartErrorsTest
What this code does
- Each lambda holds exactly one call: the one that should fail. The returned exception's message is checked, and the first test also checks the cart did not change, which is part of "rejected".
- The third test documents a design rule:
lines()returns a read-only view, soclear()throwsUnsupportedOperationExceptioninstead of emptying the real cart.
The lambda is an executable: code that JUnit runs for you inside its own try. Put only the one call that should fail inside it.
If nothing is thrown, the test fails with Expected java.lang.IllegalArgumentException to be thrown, but nothing was thrown.; a different exception type fails with Unexpected exception type thrown.
Predict the output
Pass or fail?
Pick what JUnit reports for each assertThrows.
Round 1 of 3
The code throws a different exception type.
Why try/catch/fail tests are fragile
Error path is the part of the code that runs when something goes wrong, such as rejecting a bad quantity. A test for an error path checks that the right exception is thrown for the right reason.
Before assertThrows, error tests used try, catch and fail(). Run the old style after the quantity check has been deleted and see what it reports.
Example 3 · The forgotten fail(): a test that tests nothing
public class ForgottenFailDemo { static int buggyAddQuantity(int quantity) { return quantity; // bug: the "must be at least 1" check was deleted }
static void fail(String message) { throw new AssertionError(message); }
// Old style, written correctly static String withFail() { try { buggyAddQuantity(0); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } catch (AssertionError failure) { return "FAIL (" + failure.getMessage() + ")"; } return "PASS"; }
// Old style, fail() forgotten static String withoutFail() { try { buggyAddQuantity(0); } catch (IllegalArgumentException expected) { } return "PASS"; }
public static void main(String[] args) { System.out.println("try/catch with fail(): " + withFail()); System.out.println("try/catch without fail(): " + withoutFail()); }}try/catch with fail(): FAIL (expected IllegalArgumentException) try/catch without fail(): PASS
What this code does
- The quantity check is gone, so nothing is thrown. The version with
fail()notices; the version without it reachesreturn "PASS"and reports success for a broken rule. - Nothing in the second test looks wrong at a glance, which is why
assertThrows(which fails by itself when nothing is thrown) is the standard in JUnit 5.
The hand-written shape has three traps:
- Forget the
fail()line and the test passes even when nothing is thrown: it silently tests nothing. - Catch a broad type such as
Exceptionand the test passes for the wrong error, such as aNullPointerException. - More lines between
tryandcatchmean any of them may throw, so you do not know which call raised it.
assertThrows avoids all three: one call, an exact type, and a failure when nothing is thrown.
Find the bug
Find the trap
Each hand-written error test has a trap. Tap the line to fix.
This test passes even when add accepts a quantity of 0.
assertDoesNotThrow for the happy path
assertDoesNotThrow(executable) passes when the code runs without an exception; if one is thrown, the failure message names it. A version that takes a value-returning lambda also returns that value.
A test fails anyway when its code throws. assertDoesNotThrow adds the reason: this input must be accepted.
Example 4 · assertDoesNotThrow for accepted inputs
Runs in: a Maven project with JUnit 5 (shoplite-api: src/test/java/com/shoplite/cart)
package com.shoplite.cart;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigDecimal;
import org.junit.jupiter.api.Test;
class CartAcceptsTest {
@Test void aQuantityOfOneIsAccepted() { Cart cart = new Cart();
assertDoesNotThrow(() -> cart.add("NB-A5", new BigDecimal("60.00"), 1)); }
@Test void aWellFormedPriceIsParsed() { BigDecimal price = assertDoesNotThrow(() -> new BigDecimal("17999.00")); // returns the value
assertEquals(2, price.scale()); }
@Test void aBadPriceTextFailsWithAClearMessage() { assertDoesNotThrow(() -> new BigDecimal("17,999.00")); // fails on purpose }}[ERROR] Tests run: 3, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.057 s <<< FAILURE! -- in com.shoplite.cart.CartAcceptsTest [ERROR] com.shoplite.cart.CartAcceptsTest.aBadPriceTextFailsWithAClearMessage -- Time elapsed: 0.005 s <<< FAILURE! org.opentest4j.AssertionFailedError: Unexpected exception thrown: java.lang.NumberFormatException: Character , is neither a decimal digit number, decimal point, nor "e" notation exponential mark.
What this code does
aQuantityOfOneIsAcceptedstates its purpose: 1 is the smallest valid quantity and must not be rejected. The second test shows the form that returns the lambda's result.- When the code does throw, the failure is reported as an assertion failure that names the exception, here the
NumberFormatExceptionfor a price typed with a comma.
Its main job is documentation. It says "the point of this test is that this input is accepted", for example a quantity of exactly 1, the lowest valid value.
Timeouts: assertTimeout, assertTimeoutPreemptively and @Timeout
Preemptive means stopping the code when time is up instead of waiting for it. assertTimeoutPreemptively runs the code in another thread and stops waiting at the limit, so a hanging call cannot block the test run.
A search must answer within a time limit. Compare assertTimeout, assertTimeoutPreemptively and @Timeout on a search that takes 300 ms.
Example 5 · assertTimeout, assertTimeoutPreemptively and @Timeout
Runs in: a Maven project with JUnit 5 (shoplite-api: src/test/java/com/shoplite/cart)
package com.shoplite.cart;
import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertTimeout;import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import java.time.Duration;import java.util.List;import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;import org.junit.jupiter.api.Timeout;
class SearchSpeedTest {
static List<String> search(String word, long millis) throws InterruptedException { Thread.sleep(millis); // stands in for real work return List.of("MOB-RN13", "MOB-GM35"); }
@Test void searchAnswersWithin200Ms() { List<String> skus = assertTimeout(Duration.ofMillis(200), () -> search("mobile", 20));
assertEquals(2, skus.size()); }
@Test void slowSearchFailsAfterItFinishes() { assertTimeout(Duration.ofMillis(100), () -> search("mobile", 300)); }
@Test void hangingSearchIsStoppedEarly() { assertTimeoutPreemptively(Duration.ofMillis(100), () -> search("mobile", 3000)); }
@Test @Timeout(value = 100, unit = TimeUnit.MILLISECONDS) void annotatedTestHasALimit() throws InterruptedException { search("mobile", 300); }}[ERROR] Tests run: 4, Failures: 2, Errors: 1, Skipped: 0, Time elapsed: 0.788 s <<< FAILURE! -- in com.shoplite.cart.SearchSpeedTest [ERROR] com.shoplite.cart.SearchSpeedTest.slowSearchFailsAfterItFinishes -- Time elapsed: 0.302 s <<< FAILURE! org.opentest4j.AssertionFailedError: execution exceeded timeout of 100 ms by 202 ms [ERROR] com.shoplite.cart.SearchSpeedTest.hangingSearchIsStoppedEarly -- Time elapsed: 0.104 s <<< FAILURE! org.opentest4j.AssertionFailedError: execution timed out after 100 ms [ERROR] com.shoplite.cart.SearchSpeedTest.annotatedTestHasALimit -- Time elapsed: 0.108 s <<< ERROR! java.util.concurrent.TimeoutException: annotatedTestHasALimit() timed out after 100 milliseconds
What this code does
assertTimeoutwaited for the 300 ms search to finish and then reported how far over the limit it went;assertTimeoutPreemptivelygave up after 100 ms instead of waiting 3 seconds. Both return the lambda's result when it is in time, as in the first test.@Timeoutputs the limit on the whole test method; it throws aTimeoutExceptionrather than an assertion failure, so Surefire counts it under Errors. The exact overrun numbers change from run to run; that is why timeout limits need generous margins.
Example 6 · Waiting to the end versus giving up early, in plain Java
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.TimeUnit;import java.util.concurrent.TimeoutException;
public class TimeoutStylesDemo { static String slowSearch() throws InterruptedException { Thread.sleep(1000); // a search that takes 1 second return "2 results"; }
public static void main(String[] args) throws Exception { // Like assertTimeout: run to the end in this thread, then compare the time long start = System.nanoTime(); String result = slowSearch(); long tookMs = (System.nanoTime() - start) / 1_000_000; System.out.println("same thread: got \"" + result + "\", over 200 ms limit: " + (tookMs > 200));
// Like assertTimeoutPreemptively: run in another thread and stop waiting after 200 ms ExecutorService executor = Executors.newSingleThreadExecutor(); Future<String> future = executor.submit(TimeoutStylesDemo::slowSearch); try { future.get(200, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { System.out.println("other thread: gave up after 200 ms, search cancelled: " + future.cancel(true)); } finally { executor.shutdownNow(); } }}same thread: got "2 results", over 200 ms limit: true other thread: gave up after 200 ms, search cancelled: true
What this code does
- The first style must wait the full second before it can say the limit was missed; if the search hung forever, the test would hang too.
- The second style runs the search on another thread and
future.get(200, MILLISECONDS)stops waiting at the limit, then cancels the work. That is what preemptive means, and also why the code under test runs on a different thread.
assertTimeout runs the code to the end in the same thread and then fails if it took too long. @Timeout(value = 2, unit = TimeUnit.SECONDS) on a test method or class fails any test that runs longer.
Use timeouts for code with a speed promise or a risk of hanging, such as a search that must answer within 200 ms. Keep limits generous, because build machines are slower than laptops, and prefer assertTimeout or @Timeout: preemptive code runs on another thread, which can break code that expects the test's thread, such as a Spring transaction.
Next step
Check your understanding
10 quick questions