Best way to test exceptions with Assert to ensure they will be thrown
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
The best exception test is narrow: it executes only the code expected to fail, asserts the exact exception type, and then checks the important details of the exception. Broad try-catch tests tend to hide bugs because they can pass even when the wrong line throws or when setup code fails first.
Assert the exception type directly
Most modern test frameworks provide a built-in assertion for exception testing. Use that instead of manually catching exceptions unless the framework gives you no better option.
This pattern is good because the lambda contains only the operation under test. If object construction or unrelated setup fails, the test output stays clear.
Verify the exception contents
Checking the type alone is often not enough. If the code has multiple failure modes with the same exception type, assert on the message, parameter name, or custom properties.
That extra assertion proves the code failed for the expected reason instead of just failing somewhere nearby.
Keep the failing action minimal
A common anti-pattern is putting too much code inside the exception assertion. The longer the lambda or callback, the less confidence the test gives you.
Bad pattern:
Better pattern:
The setup is now outside the assertion, so the exception check covers only the intended call.
Equivalent pattern in JUnit
The same idea applies in Java. JUnit 5 provides assertThrows, which returns the exception so you can inspect it further.
The framework-specific syntax changes, but the testing principle is the same.
Test asynchronous exceptions differently when needed
If the code returns a Task, Future, or promise-like object, use the async-specific assertion helper. A synchronous exception assertion will often inspect the wrong thing.
For example, in xUnit you would use Assert.ThrowsAsync<TException>. In JUnit, you may need to block on the future inside the assertion and assert the wrapped exception shape carefully.
The key point is that the assertion must match the execution model of the code under test.
Common Pitfalls
- Catching
Exceptionmanually and treating any failure as a passing test. - Putting setup code inside the exception assertion and letting the wrong line satisfy the test.
- Verifying only the exception type when the message or parameter name is part of the contract.
- Using synchronous exception assertions for asynchronous APIs.
- Writing tests that pass on any subclass when the code should throw one precise exception type.
Summary
- Use framework-provided exception assertions such as
Assert.ThrowsorassertThrows. - Keep only the failing operation inside the asserted callback.
- Inspect the exception object when its details matter.
- Match the assertion style to the code's execution model, especially for async code.
- Prefer precise exception assertions over broad try-catch logic.
Related reading
- C internal access modifier when doing unit testing
- c unit testing method that calls EF Core extension method
- Calculating Pearson correlation and significance in Python
- Can a unit test project load the target application's app.config file?
- Biggest GWT Pitfalls?
- Binary operator '' cannot be applied to two UIViewAutoresizing operands
- Can AWS CodePipeline track multiple feature branches and run tests on each?
- Can I access the App Store from within the iOS Simulator?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.