Spy on caught exceptions
Check which exceptions the code under test catches, and what it does with them.
Spy on catch blocks
An exception the code under test catches and ignores hides a bug from every test. Spy.Catch records each catch block the code under test enters with an exception of its type, subtypes included:
SpiedCatch<IOException> swallowed = Spy.Catch<IOException>();
saveSystem.Save();
Assert.That(swallowed.Catches, Is.Empty);
Check how the code under test handles a failure
Combine it with a stub that throws, and check the catch block that handles the exception:
Stub.Method(() => File.WriteAllText(Arg.Any<string>(), Arg.Any<string>())).Do(() => throw new IOException());
SpiedCatch<IOException> handled = Spy.Catch<IOException>();
saveSystem.Save();
Assert.That(handled.Catches, Has.Count.EqualTo(1));
Check where an exception was caught and what left the block
Each RecordedCatch holds where the block is and what left it:
Methodis the method the catch block is written in, also for anasyncmethod or an iterator. A block in a lambda or a local function names the member around it;Linetells them apart.Rethrownis the exception that left the block: the same one forthrow;, another for a wrapping throw, ornullwhen the block handled it.
Assert.That(swallowed.Catches.Where(c => c.Rethrown == null), Is.Empty);
Assert.That(swallowed.Catches.Where(c => c.Method.Name == "Save").ToList(), Has.Count.EqualTo(1));
What isn't recorded
- A
catch ... when (...)whose filter is false, since the block isn't entered. - An exception left on a task nobody awaits. Await the task in the test, and check it with NUnit.
- Catch blocks in test assemblies, which aren't woven, and catch blocks entered while a stub's answer runs.
Note:
Line is 0 when the assembly was compiled without debug
symbols.