How Do I Test a Catch Block I Can't Trigger? | Mocking with Moq

December 02, 2026
How Do I Test a Catch Block I Can't Trigger? | Mocking with Moq

This is Part 5 of the Mocking with Moq series, the companion to my VSLive 2026 "Mocking with Moq" session.
← Previous: Part 4: Should I Mock My Repository, or Use an In-Memory Fake?

Shameless plug: Honest Cheetah answers "are we on track?" for free, straight from your Azure DevOps or GitHub data, with forecasting from your real throughput. It measures the system, not the people.

▶ Watch this video on YouTube (opens in a new tab)

Somewhere in your codebase there's a catch block that has never run. Not in a test, not on your machine, maybe not even in production. Somebody wrote it for a reason, it handles some awful thing that happens once every couple of years, and nobody has ever watched it execute.

So how do you test it? You can't exactly ask the database to please fall over on cue.

Last time we looked at when a fake beats a mock. This time it's the other way around: a test that only a mock can write. And honestly, this is the reason I reach for a mock in the first place.

TL;DR

  • Code coverage will show you the branches your tests have never reached. It doesn't tell you the code is right. It tells you which code you've never watched run.
  • Setup(...).ThrowsAsync(...) makes a mocked method throw on demand. One line of setup replaces "start SQL Server and fill the disk with garbage."
  • Use xUnit's Assert.ThrowsAsync to catch the exception on the way out, then ShouldBeSameAs to check it's the same instance the mock threw, not a wrapped copy.
  • Set a breakpoint and debug the test once. Watching the scripted exception go through the handler and back out is pretty convincing.
  • The same pattern covers the specific handler and the generic catch-all.
  • No production code changed. PersonManager was already testable because the repository comes in through the constructor.

Start With Code Coverage

The app is the same one we've been working on all series. PersonManager is the business class, it gets its repository through the constructor, and the unit tests hand it a Moq mock instead of SQL Server. (If you're just showing up, Part 3 is where that got set up.)

The first thing I did was go to Test Explorer, right-click the unit tests, and run all of them with Analyze Code Coverage. Code coverage gives you an indication of which lines are exercised by your automated tests, and which ones aren't.

Twelve tests, twelve passing. Then I expanded the results down into the business dll, where we've got Logger, Person, PersonManager, the adapter, and an exception class. The one I care about is PersonManager.

Visual Studio Code Coverage Results before the new tests: PersonManager at 85.7 percent, CreateNew and FixDiskSpaceProblem at 0 percent, SaveAsync at 80 percent, and LoadByIdAsync, SaveExistingAsync and SaveNewAsync at 100 percent

Before. Most of PersonManager is green, and then there's SaveAsync.

A couple of methods are never covered at all: CreateNew and FixDiskSpaceProblem are both at zero percent. LoadByIdAsync is at one hundred percent, and so are SaveNewAsync and SaveExistingAsync.

But then there's this weird eighty percent on SaveAsync. So what's going on there?

The Catch Block Nothing Can Reach

If you want to investigate, you can double-click the method in the coverage results. That opens PersonManager with the lines highlighted according to whether they were covered, not covered, or partially covered.

Now, I'm super-duper colorblind, but I'm told that the stuff in blue is covered and the stuff in red is not covered. Either way, there's definitely a pattern to the not-covered stuff.

PersonManager.SaveAsync in the Visual Studio editor with coverage highlighting; a red box frames the catch block for SqlServerOutOfDiskSpaceException, where FixDiskSpaceProblem, the logger call and the throw are all marked as not covered

The missing twenty percent: the exception handling.

We're not running the exception handling code from our unit tests. Here's the method:

public async Task SaveAsync(Person saveThis)
{
    try
    {
        if (saveThis.Id == 0)
        {
            await SaveNewAsync(saveThis);
        }
        else
        {
            await SaveExistingAsync(saveThis);
        }
    }
    // Nothing in the app ever throws this, so no ordinary test can reach this
    // handler. A mock that throws it can.
    catch (SqlServerOutOfDiskSpaceException ex)
    {
        FixDiskSpaceProblem();
        // Problem: the logger is created right here, so a test can't check that
        // anything was logged.
        new Logger().WriteToLog(ex);
        throw;
    }
    // Any other failure: log it and rethrow.
    catch (Exception ex)
    {
        new Logger().WriteToLog(ex);
        throw;
    }
}

Catching SqlServerOutOfDiskSpaceException, fixing the disk space problem, logging it: all that stuff just isn't run from the tests.

A disclaimer: this isn't a real exception. I made it up for the sake of the demo, and "fixing" the disk space problem is a Console.WriteLine that says somebody should really do something about that database. Hopefully you understand what I'm going for here.

Somebody put this code in for a reason, so let's pretend it's something we actually want to make sure we're testing. And there's a gigantic problem: it's really hard to create that exception from a unit test.

If you wanted to test this as an integration test, you'd have to go fill up the disk and make SQL Server fall over. Doing that is impractical, hard to do, probably unreliable, and it would almost certainly annoy your sysadmins to no end.

This is where that repository interface and mocks become absolutely essential. A mock is going to let us do what would otherwise be impossible.

One Line: ThrowsAsync

Here's the shape of the test before we look at the code. The test calls SaveAsync on PersonManager. PersonManager hands the entity to the repository. The repository is a Moq mock that's been told to throw. That lands us in the catch block, and then the exception comes back out to the test.

Slide: A Failure You Can't Produce. A sequence diagram where the Test calls SaveAsync on PersonManager, PersonManager calls SaveAsync on the Repository mock, the mock throws SqlServerOutOfDiskSpaceException, the catch block runs FixDiskSpaceProblem, logs and throws, and the same exception comes back to the test for Assert.ThrowsAsync and ShouldBeSameAs

No SQL Server, no full disk, no annoyed sysadmin. Just a mock that's been told to fail.

In the video I pasted two tests into the bottom of PersonManagerFixture. Here's the first one, for the disk space exception:

// Moq move: ThrowsAsync produces a failure you can't produce for real.
// This one line replaces "start SQL Server and fill the disk with garbage."
[Fact]
public async Task SaveAsync_WhenDatabaseIsOutOfDiskSpace_RethrowsTheException()
{
    // arrange
    var expected = new SqlServerOutOfDiskSpaceException("No more room!");
    Repository.Setup(x => x.SaveAsync(It.IsAny<PersonEntity>())).ThrowsAsync(expected);

    // act
    var actual = await Assert.ThrowsAsync<SqlServerOutOfDiskSpaceException>(
        () => SystemUnderTest.SaveAsync(CreateNewPerson()));

    // assert
    actual.ShouldBeSameAs(expected, "SaveAsync should rethrow the original exception");
}

The setup for this is almost hilariously simple.

Arrange

First we create an instance of the exception. Then we take the repository mock and add a Setup for SaveAsync. It.IsAny<PersonEntity>() means I don't care which entity it is: any save is going to fail.

In the earlier posts, the thing on the end of a Setup was ReturnsAsync or a Callback. Here it's ThrowsAsync(expected). Whenever SaveAsync gets called, the mock throws our exception. That's the whole disk-filling rig.

Act

In the act phase, we wrap the call to SaveAsync in xUnit's Assert.ThrowsAsync. It's an assert that basically wraps the call in a try-catch block, and it fails the test if the exception doesn't show up.

Assert

The act phase and the assert phase get a little bit blended because of that ThrowsAsync wrapper. But just to be 100% sure, we check that the exception instance we got back is the one we expected. ShouldBeSameAs (from Benday.Common.Testing) does a compare by reference, so it has to be exactly the same instance we gave to the mock.

That's the part that proves the handler rethrows, and not just that something threw. If somebody wrapped it in a new exception on the way out, this test would catch that.

Watching It Happen in the Debugger

We're pretty much ready to run. But for the sake of the demo, I wanted to actually see it, so I put a breakpoint inside of SaveAsync, right on the call to SaveNewAsync. The person in the test has an Id of zero, so that's the path we're going to take.

Back in the test, I clicked the little diamond next to it, which brings up the test execution options dialog thingy, and picked the option to debug the test.

It runs, we hit the breakpoint, and I stepped into SaveNewAsync. It does a bunch of work: stamps the dates, runs the adapter, that's all fine. Then we get to the repository call. Hover over _repository and the tooltip tells you what it really is.

The Visual Studio debugger stopped in SaveNewAsync on the line await _repository.SaveAsync(entity), with a DataTip showing _repository is Mock of IAsyncReadableRepository of PersonEntity, int, dot Object

The repository is the mock. There's no database on the other end of this call.

The important thing to notice is that the repository is an instance of the mock. So let's run that line.

The Visual Studio debugger stopped on the catch (SqlServerOutOfDiskSpaceException ex) line in SaveAsync, with an Exception Caught popup showing Benday.MoqDemo.Business.SqlServerOutOfDiskSpaceException: 'No more room!'

"No more room!" The mock threw, and we're in the catch block that nothing else can reach.

When we make that call to SaveAsync, the mock throws the exception, and since we're in debug mode, the debugger shows us the details. Continue, and that pops us into the catch block. Now we can finally get some coverage on this exception handling logic.

Stepping through, it calls FixDiskSpaceProblem, logs the exception, and then the bare throw sends the exception back to the caller. It comes flying back out and we're back in the test code. Move down to the assert, check that the actual exception instance is the same as the expected one, and the test finishes.

Pass.

The Other Handler

The second test uses the mock in exactly the same way, with a less dramatic exception: a plain InvalidOperationException.

// The generic catch block gets the same treatment with a different exception.
[Fact]
public async Task SaveAsync_WhenSaveFailsForAnotherReason_RethrowsTheException()
{
    // arrange
    var expected = new InvalidOperationException("Something else broke.");
    Repository.Setup(x => x.SaveAsync(It.IsAny<PersonEntity>())).ThrowsAsync(expected);

    // act
    var actual = await Assert.ThrowsAsync<InvalidOperationException>(
        () => SystemUnderTest.SaveAsync(CreateNewPerson()));

    // assert
    actual.ShouldBeSameAs(expected, "SaveAsync should rethrow the original exception");
}

An InvalidOperationException isn't a SqlServerOutOfDiskSpaceException, so it skips the first handler and lands in catch (Exception ex), the one that logs and rethrows.

I ran it, and it passes. Thirty-six milliseconds, and no SQL Server anywhere.

Code Coverage, Round Two

So before, we were at eighty percent on SaveAsync because we weren't covering the catch blocks, and FixDiskSpaceProblem was at zero. Let's run the tests again with Analyze Code Coverage, now that we've got the two new ones.

Fourteen passing tests this time.

Visual Studio Code Coverage Results after the new tests: 99.4 percent overall, PersonManager at 95.2 percent, SaveAsync and FixDiskSpaceProblem both at 100 percent, and CreateNew still at 0 percent

After. SaveAsync and FixDiskSpaceProblem are both at 100%.

The overall number has gotten to almost 100%. 99.4% is pretty darned acceptable.

Drilling into the details: SaveAsync went from 80% to 100%, and FixDiskSpaceProblem went from 0% to 100%.

There's still 0% on CreateNew. In the video I said I wasn't exactly sure what was going on with that and ignored it. Having looked since: none of the unit tests call it. The fixture builds its Person objects directly. So that's a real gap, just not the one this post is about.

What Didn't Change

Using a mock let us do something that would otherwise be impractical, or maybe even impossible: injecting exceptions that come flying out of our code at strategic places, just by using Moq's ThrowsAsync. That improved our coverage by a lot, and gave us some confidence that we're actually exercising the disk space handling.

And notice what didn't change. I didn't touch production code at all. The only file that changed between the before and after folders in the demo repo is PersonManagerFixture.cs.

PersonManager was already testable, because back in Part 3 we put the repository behind an interface and passed it in through the constructor. That's what you buy with constructor injection. (If you want the reasoning behind that design, it's in Part 2.)

Recap

  • We ran the unit tests with code coverage, and SaveAsync came back at eighty percent. The missing twenty was the exception handling, starting with a catch block for SQL Server running out of disk space. Nothing in the app ever throws that.
  • The repository mock produced the failure for us: Setup on SaveAsync with It.IsAny<PersonEntity>(), then ThrowsAsync with the exception we wanted. One line, instead of filling up a disk.
  • Assert.ThrowsAsync caught the exception coming back out, and ShouldBeSameAs checked it was the very same instance the mock threw.
  • We put a breakpoint in SaveAsync and stepped through it. The mock threw, FixDiskSpaceProblem ran, the logger ran, and the bare throw sent the exception back to the test.
  • The generic catch block got the same treatment with an InvalidOperationException, and SaveAsync and FixDiskSpaceProblem both went to one hundred percent coverage.

One thing these tests can't tell us: whether anything actually got logged. The logger is created with new, right inside the handler, so the test has no way to look at it. Next time I'll inject the logger and verify that the call actually happened.

Shameless Plug

I built a tool called Honest Cheetah that answers "what are we working on?", "what's stuck?" and "are we on track?" straight from your Azure DevOps or GitHub data. It's free. Give it a try and let me know what you think.

-Ben

-- Looking for help getting an untested codebase under test, or with unit testing and architecture on your .NET team? We can help. Drop us a line at info@benday.com.


Mocking with Moq: The Full Series

More coming soon.

Related: