Testing an Expected Exception
Check the promised exception near the exact operation that should raise it. Preserve enough context to distinguish it from unrelated failures.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Keep setup outside the check
If a parser should reject "2.5" as an integer count, prepare the input and then call the parser inside the exception assertion. A setup mistake could otherwise raise the same general error before the operation begins. Conversion failure explains which operation should supply the result.
Assert stable details
A stable field identifier can be checked when callers rely on it. Avoid relying on full traceback wording unless that wording is a public contract. See reading tracebacks for how a failure can come from several call sites.[1]
Narrow the block that is expected to fail
An import test should build its fixture before asserting that parsing raises a particular error. Wrapping setup and parse together can accidentally pass if a fixture already raises the same exception. Check a stable reason or field when callers depend on it. See explicit error results.
Setup: create valid bytes containing a bad count field
Within expected exception scope: call parser
Assert error identifies field count
Inspect any expected state preservation afterward
Keep message assertions aligned with consumers
A specific human sentence may change while exception type and error code remain useful. If the exact message is part of the product contract, test it deliberately. Use an otherwise valid fixture to exercise the specific condition.