How Do I Unit Test Code That Calls the Database? Part 3: Mock the Repository | Mocking with Moq

November 24, 2026
How Do I Unit Test Code That Calls the Database? Part 3: Mock the Repository | Mocking with Moq

This is Part 3 of the Mocking with Moq series, the companion to my VSLive 2026 "Mocking with Moq" session.
← Previous: Part 2: How Do I Make My Code Mockable?

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)

You've got a class with real logic in it, and that class talks to the database. You'd like to write unit tests for the logic. But the class creates its own data access object with new, so every test you write needs SQL Server running, and now your "unit" test is slow, needs a server, and fails for reasons that have nothing to do with your code.

Last time was the map: the shape of the app, the repository interface, and why PersonManager has to ask for its repository instead of creating it. This time we type it. This is also the first post in the series where Moq actually shows up.

Two things to watch for: the build is going to break on purpose, and the tests are going to find a bug I didn't plant.

TL;DR

  • Before you refactor anything, get a safety net. Mine is a handful of integration tests that really talk to SQL Server. Everything has to keep them green.
  • Give PersonManager a constructor that takes IAsyncReadableRepository<PersonEntity, int>. Let the build break. The compiler finds every place that creates a PersonManager for you.
  • Mock<T> is the remote control. .Object is the stand-in that the class under test actually receives.
  • Setup(...).ReturnsAsync(...) scripts what the "database" hands back. It.IsAny<T>() plus Callback(...) captures what your code tried to save.
  • The id in a Setup is a filter. Call the mock with a different id and you get null back, and nobody tells you.
  • The tests found a real bug: the update path was wiping out CreateDate. Only a mock could hand me a stored record with a known CreateDate for free.

The Safety Net: Integration Tests

The solution is right where Part 1 left it, with one addition. Between that demo and this one I added an integration test project, and everything in it really talks to SQL Server.

There are two fixtures in there. SqlPersonRepositoryFixture exercises the real repository, SqlPersonRepository, with a real round trip to the database. PersonManagerIntegrationFixture exercises the old, unrefactored PersonManager, which is the thing we're about to tear into.

I ran everything in Test Explorer before touching a line of code. Nine tests, all green: the three adapter tests from Part 1, plus six integration tests that each pay for a real trip to SQL Server.

This is the safety net. Everything we do today has to keep it green.

Now that we have that, let's go break some stuff.

Add the Constructor and Break the Build

Here's the problem, as it looks in the before code. This is PersonManager loading a person:

public async Task<Person?> LoadByIdAsync(int id)
{
    var dataAccess = new PersonDataAccess();

    var entity = await dataAccess.LoadPersonAsync(id);

    if (entity == null)
    {
        return null;
    }

    var person = new Person();
    _adapter.Adapt(entity, person);

    return person;
}

That new PersonDataAccess() is the whole problem. PersonManager creates its own data access, so every call goes to SQL Server and a test has no way to substitute anything.

Right now PersonManager doesn't have a constructor. Well, it has the default one, which in C# means it doesn't take any parameters. We want one that takes a parameter, because we want to pass a repository into this class:

public class PersonManager
{
    private readonly IAsyncReadableRepository<PersonEntity, int> _repository;

    // ...

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

    // ...
}

IAsyncReadableRepository is the interface from last time (it comes from my Benday.Common library), and the two generic arguments are the entity type and the type of the primary key. SqlPersonRepository already implements it. So as long as we pass in something that implements this interface, PersonManager doesn't care what it is. That's the "ask, don't create" habit, and it's where the mock is going to go.

The moment that constructor exists, there's a compiler error. The integration fixture creates a PersonManager with no arguments, and there isn't one of those anymore.

That's expected. We're breaking how it all works on purpose, and that's the beginning of the refactoring. I'm not adding a temporary parameterless constructor to make the error go away, and I'm not passing null! to shut the compiler up. The errors are a to-do list. We'll come back to them.

(The unit test project doesn't reference the integration test project, so it still builds and runs while that error sits there.)

The First Unit Test with a Mock

Over in the unit test project, I added a new class called PersonManagerFixture. It derives from TestClassBase, the base class from my Benday.Common.Testing library that we used in Part 1. The constructor just takes the output helper from xUnit so the base class can do things like logging.

The system under test for this fixture is a PersonManager. And PersonManager now wants something that implements IAsyncReadableRepository<PersonEntity, int>. We don't have that. This is where Moq comes in:

public class PersonManagerFixture(ITestOutputHelper output) : TestClassBase(output)
{
    // One mock per constructor parameter. Mock<T> is the remote control you
    // configure and verify; .Object is the stand-in that PersonManager receives.
    private Mock<IAsyncReadableRepository<PersonEntity, int>> Repository => field ??= new();

    // The real PersonManager, built with the stand-in.
    private PersonManager SystemUnderTest => field ??= new PersonManager(Repository.Object);

    // ...
}

Two lines, and they're the two halves of every Moq test you'll ever write.

Repository is a Mock<T>. That's me saying "I want a mocked instance of this interface." It's the remote control: the thing the test talks to when it wants to describe behavior.

Repository.Object is the generated instance that Moq builds from the interface. That's the stand-in, and that's what PersonManager gets and uses. PersonManager never sees the Mock<T>. It just sees something that implements the interface it asked for.

We haven't told the mock to do anything yet, and the compiler is perfectly happy.

Setup and ReturnsAsync

Here's the first test. When the person exists, LoadByIdAsync returns the person.

[Fact]
public async Task LoadByIdAsync_WhenPersonExists_ReturnsThePerson()
{
    // arrange
    Repository.Setup(x => x.GetByIdAsync(1)).ReturnsAsync(CreateExistingEntity());

    // act
    var actual = await SystemUnderTest.LoadByIdAsync(1);

    // assert
    actual.ShouldNotBeNull("person 1 exists, so it should load");
    actual.Id.ShouldEqual(1, "Id should come from the repository");
    actual.FirstName.ShouldEqual(TestConstants.FirstName, "FirstName should come from the repository");
    actual.LastName.ShouldEqual(TestConstants.LastName, "LastName should come from the repository");
}

Setup describes the behavior we want from the mocked instance. In this case: if somebody calls GetByIdAsync and passes an argument of 1, then ReturnsAsync this entity.

And yes, that 1 actually matters. It's a filter. The setup only answers a call made with exactly 1. Call it with anything else and you get null back, and nobody tells you. So a mismatched id in a test doesn't look like a broken test. It looks like a bug in your code.

What the mock hands back is CreateExistingEntity(), a little helper in the fixture:

// What the "database" hands back for person 1.
private static PersonEntity CreateExistingEntity() => new()
{
    Id = 1,
    FirstName = TestConstants.FirstName,
    LastName = TestConstants.LastName,
    EmailAddress = TestConstants.EmailAddress,
    CreateDate = TestConstants.CreateDate,
    LastModified = TestConstants.CreateDate
};

Remember, if the Id is anything other than zero, that means it's already been saved. So we're pretending the database is handing back a saved entity. There is no database.

Then the act and the assert are about the actual logic in PersonManager. We call LoadByIdAsync, and what comes back is not a PersonEntity. It's a Person business object. That coordination (load the entity, check for null, run the adapter, return the person) is the thing we're testing.

One small thing about those assertions: ShouldNotBeNull and friends come from Benday.Common.Testing and they carry [NotNull], so after that first line the compiler knows actual isn't null. No ! operator anywhere in the test.

Red, Then Refactor

So I ran it. And it failed.

It tried to open a SQL connection. Of course it did: LoadByIdAsync still news up PersonDataAccess. We gave PersonManager a repository and it's ignoring it.

The fix is the version you'd expect:

public async Task<Person?> LoadByIdAsync(int id)
{
    var entity = await _repository.GetByIdAsync(id);

    if (entity == null)
    {
        return null;
    }

    var person = new Person();
    _adapter.Adapt(entity, person);

    return person;
}

I put a breakpoint on that first line and debugged the test, because I think it's worth watching the mock do its thing once.

Visual Studio debugger stopped on the _repository.GetByIdAsync line in PersonManager.LoadByIdAsync, with the call stack showing it was called from the unit test LoadByIdAsync_WhenPersonExists_ReturnsThePerson

Stopped inside PersonManager, called from the unit test. That _repository is the mock's .Object.

If you hover over _repository at that point, it isn't a SqlPersonRepository. It's the .Object of a Mock<IAsyncReadableRepository<PersonEntity, int>>. That's the stand-in. When that line executes, GetByIdAsync doesn't go anywhere near a database. It just hands back what we set up in the test. Step over it, is the entity null? No. Run the adapt logic, return the person.

All of the assertions pass, and that test is green with no SQL Server anywhere.

Load Returns Null

The second test is the same setup with a different answer. What does LoadByIdAsync do when you ask for a person that doesn't exist?

[Fact]
public async Task LoadByIdAsync_WhenPersonDoesNotExist_ReturnsNull()
{
    // arrange
    Repository.Setup(x => x.GetByIdAsync(2)).ReturnsAsync((PersonEntity?)null);

    // act
    var actual = await SystemUnderTest.LoadByIdAsync(2);

    // assert
    actual.ShouldBeNull("there is no person 2");
}

"The database has no person 2," in one line, without a database. That's really what a mock is: a scripted answer.

In the video, just for the sake of giggles, I added a second setup to this test so that id 1 returns an entity and id 2 returns null. Same mock, two different answers depending on the argument. It passes on the first try, and it's the filter idea again, on screen.

The Save Tests

Loading is the easy direction. The mock returns something and you check what your code did with it. Saving is the other way around: your code hands something to the repository, and the test needs to see what it was.

[Fact]
public async Task SaveAsync_WhenPersonIsNew_SavesTheFieldsToTheRepository()
{
    // arrange
    PersonEntity? saved = null;
    Repository.Setup(x => x.SaveAsync(It.IsAny<PersonEntity>()))
        .Callback<PersonEntity>(entity => saved = entity);
    var person = CreateNewPerson();

    // act
    await SystemUnderTest.SaveAsync(person);

    // assert
    saved.ShouldNotBeNull("SaveAsync should hand the repository an entity");
    saved.FirstName.ShouldEqual(TestConstants.FirstName, "FirstName should be saved");
    saved.LastName.ShouldEqual(TestConstants.LastName, "LastName should be saved");
    saved.EmailAddress.ShouldEqual(TestConstants.EmailAddress, "EmailAddress should be saved");
}

Two new pieces of Moq here.

It.IsAny<PersonEntity>() means we don't care what gets passed in. Whatever entity comes to us, we're happy with it. (Compare that with the literal 1 and 2 in the load tests, where we cared a lot.)

Callback is what we do instead of returning something. It takes a lambda, and that lambda gets whatever was passed to the mock. Here it stuffs it into the saved variable. So it takes whatever PersonManager hands to the repository and captures it, and the test can look at it afterwards.

CreateNewPerson() builds a Person with an Id of zero, which means it hasn't been saved yet. We call SaveAsync on the system under test, somewhere inside PersonManager it calls SaveAsync on the repository, and then we check that the adapter adapted the right stuff and the thing we tried to save matches what we expected.

The Callback Plays the Database

A callback can do more than capture. In a real save, the database assigns the Id. So in the next test, the callback pretends to be the database's insert:

Repository.Setup(x => x.SaveAsync(It.IsAny<PersonEntity>()))
    .Callback<PersonEntity>(entity => entity.Id = 42);
var person = CreateNewPerson();

// act
await SystemUnderTest.SaveAsync(person);

// assert
person.Id.ShouldEqual(42, "Id should come back from the repository");

The mock stamps the entity with 42, and PersonManager is supposed to copy that back onto the Person.

The Audit Dates

Person and PersonEntity both carry two fields for auditing, CreateDate and LastModified. There's a test for a brand new person (after the save, both dates should no longer be the plain old default DateTime, and the saved entity should carry the same values as the Person). We can't check the exact time yet, because the clock is still DateTime.UtcNow. That's a later episode.

Then there's the one for an existing person, and this is the one to pay attention to:

[Fact]
public async Task SaveAsync_WhenPersonExists_DoesNotChangeCreateDate()
{
    // arrange
    PersonEntity? saved = null;
    Repository.Setup(x => x.GetByIdAsync(1)).ReturnsAsync(CreateExistingEntity());
    Repository.Setup(x => x.SaveAsync(It.IsAny<PersonEntity>()))
        .Callback<PersonEntity>(entity => saved = entity);
    var person = CreateNewPerson();
    person.Id = 1;
    person.Notes = TestConstants.Notes;

    // act
    await SystemUnderTest.SaveAsync(person);

    // assert
    person.CreateDate.ShouldEqual(TestConstants.CreateDate, "CreateDate should come from the stored record");
    saved.ShouldNotBeNull("SaveAsync should hand the repository an entity");
    saved.CreateDate.ShouldEqual(TestConstants.CreateDate, "CreateDate should not change on an update");
    saved.Notes.ShouldEqual(TestConstants.Notes, "Notes should be saved on an update");
}

Two setups on one mock. GetByIdAsync(1) returns CreateExistingEntity(), which looks like a record that's already been saved, CreateDate and all. SaveAsync captures whatever gets saved, same as before. Remember, this is all in memory.

Then the Person we're saving: Id of 1, a non-blank note. And notice, we never set a CreateDate on it.

After the save, CreateDate should not have changed. It should still be the stored one.

I ran all of these from Test Explorer to see how far we'd get. The answer was: not very far. An awful lot of red X's, and every save test failing for the same reason as before. The save paths still use the old PersonDataAccess.

Refactor the Save Paths

Same move as the load. Two places still new up PersonDataAccess, one in SaveNewAsync and one in SaveExistingAsync. Here's SaveNewAsync afterwards:

private async Task SaveNewAsync(Person saveThis)
{
    // Problem: the real clock. A test can't know what time this will be.
    saveThis.CreateDate = DateTime.UtcNow;
    saveThis.LastModified = DateTime.UtcNow;

    var entity = new PersonEntity();
    _adapter.Adapt(saveThis, entity);

    await _repository.SaveAsync(entity);

    saveThis.Id = entity.Id;
}

In SaveExistingAsync, the load becomes _repository.GetByIdAsync and the save at the bottom becomes _repository.SaveAsync.

Run the tests again. A lot more passing now. But one is still failing.

The CreateDate Bug

SaveAsync_WhenPersonExists_DoesNotChangeCreateDate. And that should not be failing. I just did a mechanical swap of one data access call for another.

Test Explorer showing six passing tests and one failure, SaveAsync_WhenPersonExists_DoesNotChangeCreateDate, with the message Expected 1/15/2026 9:00:00 AM, Actual 1/1/0001 12:00:00 AM

Expected January 15th, 2026. Actual: January 1st of the year 1.

Look at the message. Expected 1/15/2026, which is the CreateDate the mock handed back. Actual, 1/1/0001.

Here's why. SaveExistingAsync loads the stored entity, and that entity has the real CreateDate on it. Then the adapter copies every field from the Person onto that entity, including a CreateDate the caller never set. So the default DateTime gets written right over the stored value.

That's not a bug in my refactoring. That's a bug that was already in the code. The update path was wiping out CreateDate.

The fix is one line, right before the adapter runs:

private async Task SaveExistingAsync(Person saveThis)
{
    var entity = await _repository.GetByIdAsync(saveThis.Id)
        ?? throw new InvalidOperationException("Unknown person.");

    // The database owns CreateDate. The stored value wins over whatever the
    // caller's copy says, so an update can't wipe it out.
    saveThis.CreateDate = entity.CreateDate;
    saveThis.LastModified = DateTime.UtcNow;

    _adapter.Adapt(saveThis, entity);

    await _repository.SaveAsync(entity);
}

CreateDate should not change for existing person records. The database owns it. So whatever we loaded back, preserve that value before we do the adapt.

Run it again: all seven green.

This is the kind of test where mocking really pays off. You get to work on exactly the data you want without having to make it happen in the database first. I wanted "a stored record with this specific CreateDate, and a caller who doesn't know it," and the mock gave me that in one line.

There's one more test in the fixture, for the other branch of that method. The repository returns null for id 2, we try to save a person with an Id of 2, and we use xUnit's Assert.ThrowsAsync to check that SaveAsync throws an InvalidOperationException with the message "Unknown person."

Fixing the Rest of the Code

Remember the compiler error we walked away from? Time to pay up. I rebuilt the whole solution and got two errors, and they're the two places that create a PersonManager: the integration fixture and Program.cs.

That's the compiler finding the composition root for me. I didn't have to go searching. Both of them get the real repository:

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

That's the line in Program.cs. The integration fixture's CreatePersonManager() gets the same new SqlPersonRepository(new PersonDbContext()), and it's the only line in that fixture that changes.

Then I ran everything, unit tests and integration tests together. It compiles, and all sixteen pass. The safety net is still green.

Drop the DataAccess Reference

One last thing I promised at the start: proving that Business doesn't depend on the database.

PersonEntity lives in the Common project now (that was part of the setup from last time), and PersonManager only knows about the interface. So the Business project doesn't need its project reference to DataAccess anymore. I took it out, and this is the whole Business project file afterwards:

<Project Sdk="Microsoft.NET.Sdk">
  <ItemGroup>
    <ProjectReference Include="..\Benday.MoqDemo.Common\Benday.MoqDemo.Common.csproj" />
  </ItemGroup>
</Project>

The console app was getting DataAccess through Business, so it needs its own reference now. That makes sense: it's the one that creates the real SqlPersonRepository. Rebuild, rerun.

The Business project file with the DataAccess project reference commented out, next to Test Explorer showing all 16 tests passing: 6 integration tests and 10 unit tests

The DataAccess reference is out of the Business project, and all sixteen tests are still green.

And PersonDataAccess, the old class, is gone from the after code. Nothing uses it. With that reference removed, a unit test of PersonManager can't reach SQL Server even by accident.

A couple of the tests have the same names in both projects, by the way, like SaveAsync_WhenPersonExists_DoesNotChangeCreateDate. Same behavior, two projects. One needs SQL Server, one doesn't. That's the whole point.

Recap

  • We started with the integration tests as a safety net, and they stayed green the whole way.
  • We put the database behind IAsyncReadableRepository<PersonEntity, int> and passed it in through PersonManager's constructor.
  • We let the build break on purpose, and the compiler pointed at the two places that create a PersonManager. Both got the real SqlPersonRepository.
  • We wrote seven tests with one mock: Setup and ReturnsAsync for the loads, It.IsAny and Callback for the saves, including the one where the callback plays the database and assigns the Id.
  • Each method went red, then green as we moved it from PersonDataAccess to _repository.
  • The tests found a real bug: the update path was copying the caller's CreateDate over the one in the database. Only a mock could hand us a stored record with a known CreateDate to prove it.
  • The Business project no longer references DataAccess.

Every test today scripted the database, one Setup at a time. Next time I'll write the one test where that gets silly, and show you the little fake class that fixes it: mock versus fake.

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: