How Do I Verify a Method Was Called With Moq? | Mocking with Moq

December 04, 2026
How Do I Verify a Method Was Called With Moq? | Mocking with Moq

This is Part 6 of the Mocking with Moq series, the companion to my VSLive 2026 "Mocking with Moq" session.
← Previous: Part 5: How Do I Test a Catch Block I Can't Trigger?

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)

Some requirements aren't return values. "When the save fails, the error gets logged" is one of them. There's no result to compare and no property to check. The only evidence that it happened is that one object called a method on another object.

So how do you write a test for that?

Last time we used a mock to throw an exception that nothing in the app can produce, and we proved it came back out of SaveAsync. What we couldn't prove is that anything got logged on the way. Today that takes one more constructor parameter, and a Moq method called Verify.

TL;DR

  • Behavior verification checks the interaction between a class and its dependency: did this call happen, with this argument, this many times?
  • Verify(..., Times.Once) proves a call happened. Verify(..., Times.Never) proves it didn't, and that's the one people forget.
  • Pass the actual object instead of It.IsAny<T>() and you prove the call happened with the value that matters. The exception you caught is the exception you logged.
  • You can only verify a call on something the test handed in. new Logger() inside a catch block is invisible to the test, so the logger becomes an ILogger that comes in through the constructor.
  • Let the compiler find the call sites. Add the constructor parameter and the Error List becomes your to-do list.
  • Verify the calls that are the requirement. Verify everything, and every refactor breaks ten tests.

Two Lines That Say new Logger

The app is the same one we've been working on all series. PersonManager is the business class, and it gets its repository through the constructor. Down in the exception handling of SaveAsync, when the database is out of disk space, we not only fix the problem, we've also got this logger. We say new Logger().WriteToLog(ex). And if it's any other exception, we write to the log the same way.

PersonManager.SaveAsync in the Visual Studio editor with red boxes around the two lines that say new Logger().WriteToLog(ex), one in the catch block for SqlServerOutOfDiskSpaceException and one in the catch block for Exception

Two catch blocks, and both of them create their own logger.

So here's another place where we're new-ing up a dependency and doing something important. That makes it our next testability refactoring.

What Behavior Verification Is

Sometimes what you want to do in a unit test is verify that a particular call happened. Here, the save fails, PersonManager calls WriteToLog on the logger, and the exception comes back out. Nothing that comes back to the test says whether that log call was ever made.

Slide: Behavior Verification. A sequence diagram where the Test calls SaveAsync on PersonManager, PersonManager calls SaveAsync on the Repository mock, the mock throws, PersonManager calls WriteToLog on the Logger mock with a note reading intent: this call must happen, the exception is rethrown to the test, and the test then asks the Logger mock: was WriteToLog called?

So the test asks the mock afterwards: did that call happen? This is called behavior verification, and what it checks is the interaction between a class and its dependency. Some people like it and some people hate it.

I think it's really helpful in those cases where you want to make sure that no one accidentally removes or changes some code that you thought was important. What you end up doing inside your unit test is recording your intent. I intend that this code works in this particular way, and I'm expecting a call to happen in this particular place.

To verify that call, the test has to get in between PersonManager and the logger, and that means injecting it.

Four Verify Tests

In the video I pasted four tests into the bottom of PersonManagerFixture and then walked through them. They don't compile yet. I know why, and we'll fix it in a minute. First, here's what they do.

Times.Once

// Moq move: Verify(..., Times.Once) checks the call happened. This is what makes a stub a mock.
[Fact]
public async Task SaveAsync_WhenPersonIsNew_SavesThroughTheRepository()
{
    // arrange
    var person = CreateNewPerson();

    // act
    await SystemUnderTest.SaveAsync(person);

    // assert
    Repository.Verify(x => x.SaveAsync(It.IsAny<PersonEntity>()), Times.Once);
}

This first one verifies some behavior on the repository. We create a new person and call SaveAsync on the system under test. That should produce exactly one call to SaveAsync on the repository. We don't care what the argument is, so we say It.IsAny<PersonEntity>(). And then Times.Once, meaning we should get one call and only one.

This test doesn't need any changes to the production code at all, because the repository is already a mock. And this is the move that turns a stub into a mock. Up to now the repository mock has been answering questions: return this entity, throw this exception. But the mock also remembers every call it got, and Verify asks it afterwards: did this happen, and how many times?

Times.Never

// Moq move: Times.Never checks something did NOT happen.
[Fact]
public async Task SaveAsync_WhenPersonIsNew_DoesNotLog()
{
    // arrange
    var person = CreateNewPerson();

    // act
    await SystemUnderTest.SaveAsync(person);

    // assert
    Logger.Verify(x => x.WriteToLog(It.IsAny<Exception>()), Times.Never);
}

This is a slightly different way of verifying behavior. If the save is successful, I want to verify that, no, we did not call that log method. Any exception at all, zero times.

Proving something did not happen is just as much a requirement as proving it did. This is the test that catches the bug where somebody moves the log call out of the catch block and it starts firing on the happy path too.

The Exact Exception

// Verify with a specific argument: the exception that was thrown is the one that got logged.
[Fact]
public async Task SaveAsync_WhenDatabaseIsOutOfDiskSpace_LogsTheException()
{
    // arrange
    var expected = new SqlServerOutOfDiskSpaceException("No more room!");
    Repository.Setup(x => x.SaveAsync(It.IsAny<PersonEntity>())).ThrowsAsync(expected);

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

    // assert
    Logger.Verify(x => x.WriteToLog(expected), Times.Once);
}

This one does a couple of things at once. First, we make the repository throw using Setup and ThrowsAsync, same as last time. Then we check that the exception comes back out, using xUnit's Assert.ThrowsAsync.

And then we verify that WriteToLog was called exactly once, with the exception that we threw up above. Not It.IsAny this time. The exact object.

So this isn't exactly testing the out of disk space handling. It's verifying that we're logging it the way we'd expect, and yeah, I think that's kind of important. The exception you caught is the exception you log.

And the Other Handler

// The generic catch block logs too.
[Fact]
public async Task SaveAsync_WhenSaveFailsForAnotherReason_LogsTheException()
{
    // arrange
    var expected = new InvalidOperationException("Something else broke.");
    Repository.Setup(x => x.SaveAsync(It.IsAny<PersonEntity>())).ThrowsAsync(expected);

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

    // assert
    Logger.Verify(x => x.WriteToLog(expected), Times.Once);
}

Same thing for the generic catch block: any other exception gets logged as well, one time, and it's the one we threw.

Logger Does Not Contain a Definition for Verify

When I build the solution, well, we've got some issues.

The Visual Studio editor showing the first two Verify tests, with the Error List underneath showing three CS0117 errors: 'Logger' does not contain a definition for 'Verify', all in PersonManagerFixture.cs

Three errors, all the same.

Three of them, all the same: 'Logger' does not contain a definition for 'Verify'. The reason is that the fixture doesn't have a logger mock at all. So the compiler is finding the Logger class over in Business instead, and that class has no Verify method.

Notice that it's three errors and not four. The Times.Once test on the repository compiles just fine.

Extract ILogger

Up at the top of the fixture, next to the repository mock, I added a second one with the same shape:

private Mock<ILogger> Logger => field ??= new();

That gets a red squiggle, because there's no such thing as ILogger yet. When I pulled up the quick actions, Visual Studio offered me the one from the Microsoft logging framework, and ordinarily that's probably what I'd use. But for the sake of this demo I wrote my own, so you can see the whole thing with nothing hidden.

It goes in the Common project, and it has exactly one method:

namespace Benday.MoqDemo.Common;

// Extracted from Logger so PersonManager can depend on an interface, and tests
// can pass a Mock<ILogger>.
public interface ILogger
{
    void WriteToLog(Exception ex);
}

Then the existing Logger class in Business, the one that writes to the console, says that it implements ILogger:

public class Logger : ILogger
{
    public void WriteToLog(Exception ex)
    {
        Console.Error.WriteLine($"{ex.GetType().Name}: {ex.Message}");
    }
}

That's the whole interface extraction. Logger already had the method. It just needed to say so.

Inject It, and Let the Compiler Find the Call Sites

Now over to PersonManager. The logger becomes the second constructor parameter, with a private readonly field for it right underneath the repository field:

private readonly IAsyncReadableRepository<PersonEntity, int> _repository;
private readonly ILogger _logger;

public PersonManager(
    IAsyncReadableRepository<PersonEntity, int> repository,
    ILogger logger)
{
    _repository = repository;
    _logger = logger;
}

Same pattern as the repository: the field holds whatever the constructor was handed, and PersonManager never news one up itself.

Scroll down and the two catch blocks are still saying new Logger(). And actually, I didn't fix those yet. Hold that thought, because the Error List has moved on.

PersonManager.cs with the Error List showing three CS7036 errors: There is no argument given that corresponds to the required parameter 'logger' of 'PersonManager.PersonManager(IAsyncReadableRepository of PersonEntity, int, ILogger)', at lines 19, 186 and 210 of PersonManagerFixture.cs

The compiler just made the list of every place that creates a PersonManager.

Now there are three places that call the PersonManager constructor without a logger. I didn't have to go hunting for them. Double-click the error and it takes you there.

The first one is SystemUnderTest in the fixture. We've got the logger mock right there, so it goes in as the second argument:

private PersonManager SystemUnderTest => field ??=
    new PersonManager(Repository.Object, Logger.Object);

The other two are the InMemoryRepository tests from Part 4, where the test builds its own PersonManager with the fake. Those get Logger.Object too, to make the compiler happy.

Build again, and the errors move out of the test project into the last two places. Program.cs in the console app is the composition root, the one place that creates the real dependencies, so there it's the real thing:

var manager = new PersonManager(new SqlPersonRepository(new PersonDbContext()), new Logger());

And the integration test fixture gets the same fix, new Logger(), the real one, because those tests run against the real SQL Server.

Now it compiles.

Red for the Right Reason

So I went over to Test Explorer and ran the unit tests. Sixteen passed, two failed.

x.WriteToLog(SqlServerOutOfDiskSpaceException: No more room!)" class="border border-dark" />

This is what a failed Verify looks like.

The out of disk space test fails with a Moq.MockException: expected invocation on the mock once, but was 0 times. So the save threw, and nothing ever called WriteToLog on the mock. It's the same thing for the generic exception test.

Weird? Well, not really. PersonManager is still saying new Logger() in both catch blocks, so the log call went to a brand new console logger and the mock never heard about it. The constructor takes a logger and then ignores it.

That's exactly the bug a behavior verification test exists to catch, and it's a good place to be. We're starting from a failing test and making it go towards a passing one.

Green

Back in PersonManager, I selected new Logger(), pulled up find and replace, and changed it to _logger. Not in the entire solution, just in the current document, because Program.cs and the integration fixture really do want new Logger().

catch (SqlServerOutOfDiskSpaceException ex)
{
    FixDiskSpaceProblem();
    _logger.WriteToLog(ex);
    throw;
}
// Any other failure: log it and rethrow.
catch (Exception ex)
{
    _logger.WriteToLog(ex);
    throw;
}

Replace all, two places changed, and both catch blocks now log through the injected logger. Build, rerun.

PersonManager.cs after the find and replace, with _logger.WriteToLog(ex) in both catch blocks, and Test Explorer showing all 15 tests in PersonManagerFixture passing, including both LogsTheException tests and DoesNotLog

Both catch blocks use the injected logger, and all fifteen tests in the fixture pass.

Everything's passing.

What a Verify Is For

One more thing, because behavior verification is easy to overdo.

Slide: What a Verify Is For. Three bullets: Verify the calls that are the requirement. Verify everything, and every refactor breaks ten tests. Get the dance right before the partner exists.

Verify the calls that are the requirement. When the save fails, the error gets logged. That's a rule the business would state out loud, so it gets a verify.

Verify everything, and every refactor breaks ten tests. I know what you're thinking: why not verify all of it while I'm in there? Because then the tests are pinned to how the code does its job and not what it's supposed to do. Every refactor breaks a pile of tests that weren't protecting anything, and people start deleting tests instead of fixing code.

Get the dance right before the partner exists. There's a slightly more sophisticated place where I use this. Sometimes I know my code is going to need to call another system in a particular way, and that system hasn't been built yet, or it's optional. Behavior verification lets me make sure the dance is right before the other dancer shows up.

So verify the thing the business cares about, and the test reads like a requirement.

Recap

  • We pulled an ILogger interface out of the Logger class, put it in Common, and had Logger implement it.
  • PersonManager takes it through the constructor, and the compiler found every call site for us: the fixture, the console app and the integration tests.
  • Times.Once verified that the repository was asked to save exactly once, and Times.Never verified that the logger wasn't called on the happy path.
  • In both failure tests, we verified that the exception we threw is the one that got logged, by passing the actual object instead of It.IsAny.
  • The tests went red with a MockException while PersonManager was still saying new Logger(), and green once both catch blocks used the injected one.

Next time: PersonManager still reads DateTime.UtcNow, so the tests can't pin a date. The fix is a clock through the constructor, and .NET already built the seam for you.

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: