Should I Mock My Repository, or Use an In-Memory Fake? | Mocking with Moq

November 30, 2026
Should I Mock My Repository, or Use an In-Memory Fake? | Mocking with Moq

This is Part 4 of the Mocking with Moq series, the companion to my VSLive 2026 "Mocking with Moq" session.
← Previous: Part 3: Mock the Repository

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)

Last time, every single test scripted the database with a Moq mock, and that worked great. Person 1 exists. Person 2 doesn't. Capture what got saved. One Setup each, done.

Then you go to write the most ordinary test there is: save a person, load it back, and expect to get what you saved. And scripting the database starts to get silly.

This post is about the tests where Moq is the wrong tool, and the little class that makes them easy.

TL;DR

  • A mock is a scripted answer with no memory. A fake is a real, working implementation that takes a shortcut.
  • The moment a test cares about state across calls (save then load, save twice), a mock makes you re-implement the database inside the test.
  • InMemoryRepository<PersonEntity> from my Benday.EfCore.Testing package implements the same IAsyncReadableRepository<PersonEntity, int> interface as the real SQL Server repository. PersonManager can't tell the difference.
  • There's no magic inside it: a List<T>, sequential Ids, and a save that adds to the list.
  • The rule I use: mock when you need an answer you can't produce for real, fake when you need state. Verify behavior with a mock, verify data with a fake.

The Test Where Scripting Gets Silly

Quick refresher on where we are. PersonManager takes its repository through the constructor, as an interface:

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

That's the change that makes the code mockable. In the unit tests, that parameter gets the .Object of a Mock<T>, and each test tells the mock what to say.

Now think about a round trip test. Save a person, then load that person by Id. With a mock, SaveAsync doesn't save anything and GetByIdAsync doesn't know anything, so you have to wire the two together yourself. The demo repo's README has the version you'd end up with:

PersonEntity? stored = null;
Repository.Setup(x => x.SaveAsync(It.IsAny<PersonEntity>()))
    .Callback<PersonEntity>(entity => { entity.Id = 1; stored = entity; });
Repository.Setup(x => x.GetByIdAsync(1))
    .ReturnsAsync(() => stored);

A Callback to capture the entity and stamp an Id on it, and a second Setup to hand it back. It works. It's also a database. A very small one that lives inside your unit test, and every test that needs a round trip gets to build its own.

(In the video I skip straight to the better version. This snippet is in the README for anyone who wants to feel the pain first.)

A Round Trip Test With No Mock

Here's the same test with no Moq in it at all:

[Fact]
public async Task LoadByIdAsync_AfterSaveAsync_ReturnsTheSavedPerson()
{
    // arrange
    var sut = new PersonManager(new InMemoryRepository<PersonEntity>());
    var saved = CreateNewPerson();
    saved.Notes = TestConstants.Notes;
    await sut.SaveAsync(saved);
    saved.Id.ShouldNotBeZero("the fake should assign an Id on save");

    // act
    var actual = await sut.LoadByIdAsync(saved.Id);

    // assert
    actual.ShouldNotBeNull("the saved person should load back");
    actual.Id.ShouldEqual(saved.Id, "the fake should assign an Id and hand it back");
    actual.FirstName.ShouldEqual(TestConstants.FirstName, "FirstName should round-trip through the fake");
    actual.LastName.ShouldEqual(TestConstants.LastName, "LastName should round-trip through the fake");
    actual.Notes.ShouldEqual(TestConstants.Notes, "Notes should round-trip through the fake");
}

It's an ordinary and boring test. Create a new person, populate the notes, call SaveAsync, load it back by Id, and check that the right stuff came back: the Id, the first name, the last name and the notes.

The only interesting bit is up in the arrange. Instead of a mock, PersonManager is getting a class called InMemoryRepository. It pretends to be an in-memory version of the database.

I added that ShouldNotBeZero check after the save while I was recording. It just verifies that the fake really did hand out an Id, and that we're not doing something crazy, before the test goes on to use that Id.

Run it, and it passes.

Visual Studio showing LoadByIdAsync_AfterSaveAsync_ReturnsTheSavedPerson passing with a duration of 70 ms

Seventy milliseconds, and it all happened in memory. (The code on screen is my live take; the listing above is the cleaned-up version in the repo.)

One more thing about that test name. LoadByIdAsync_AfterSaveAsync_ReturnsTheSavedPerson is also the name of a test in the integration test project, and that's on purpose. It's the same test with the same kind of assertions. One runs against SQL Server and one runs against a list.

Mock Versus Fake

I can read your mind, and I can tell that you're thinking, "yeah, so why not just use a mock?"

The answer is that testing with mocks can sometimes be a pain because of tedious, annoying, or repetitive setup logic. So here, I'm using a fake instead of a mock.

Now, I generally dislike wrestling with pedantic little distinctions between terms. But I think this one is worth pointing out.

Slide: Mock Versus Fake. Why not just use a mock? A mock is a scripted answer with no memory. A fake is a working implementation with a shortcut. PersonManager can't tell the difference.

A mock returns a scripted answer. You tell it what to return, and when it's asked that particular question, it returns that answer. It has no memory of anything else.

A fake is a real, working implementation that takes some kind of a shortcut. For the in-memory repository, the shortcut is a collection stored in memory that pretends to save to SQL Server. It's not actually saving to SQL Server, but the save really does store something, and the load really does find that thing again.

And PersonManager doesn't care. It also can't tell the difference, because all it ever sees is the C# interface. That's the whole reason the constructor takes an interface instead of a class.

So I regret to inform you that there is indeed a meaningful difference between a mock and a fake. But rather than worrying about who's right about the terminology, focus on what your test needs and what makes the most sense for testability.

Three Things, One Interface

Here's the picture from last time, with one more box in it.

Slide: Three Things, One Interface. A class diagram with PersonManager depending on IAsyncReadableRepository of PersonEntity and int through its constructor, implemented by SqlPersonRepository (EF Core, SQL Server), InMemoryRepository of PersonEntity (a List, in memory) and Mock of T dot Object (scripted by the test).

SqlPersonRepository is the real one: EF Core against SQL Server. Mock<T>.Object is the one the tests scripted in Part 3. And the new one in the middle is InMemoryRepository<PersonEntity>, from my Benday.EfCore.Testing package. It implements the exact same interface, so it drops into the same constructor.

Three things that satisfy one interface, and PersonManager works with any of them. No production code changes in this episode at all. Only tests.

Inside InMemoryRepository

If you go to the definition of InMemoryRepository, well, it is not very fancy.

The one I used in the test, InMemoryRepository<T>, is just a convenience shim for integer keys. The real thing is one level up, InMemoryRepository<T, TIdentity>:

public class InMemoryRepository<T, TIdentity> : IAsyncReadableRepository<T, TIdentity>
    where T : EntityBase<TIdentity>
    where TIdentity : IEquatable<TIdentity>
{
    private int _nextIdCounter = 1;

    /// <summary>The backing store of saved entities.</summary>
    public List<T> Items { get; set; } = new();

    // ...
}

The entire thing about how this works is that there's a collection of items in memory. Items is a plain List<T>, whatever T is. In this case, PersonEntity. That list is the "table".

Below that there's some bookkeeping: WasSaveCalled, WasGetByIdCalled, SaveArgumentValue, that kind of thing, so a test can check what got called if it wants to. And then there's a little GenerateId method that hands out sequential Ids: one, two, three. The same thing SQL Server would do, just predictable.

Here's the save and the load:

public Task<T?> GetByIdAsync(TIdentity id)
{
    WasGetByIdCalled = true;
    GetByIdArgumentValue = id;

    var match = Items.FirstOrDefault(item => item.Id.Equals(id));
    return Task.FromResult(match);
}

public Task SaveAsync(T entity)
{
    WasSaveCalled = true;
    SaveArgumentValue = entity;

    if (IsNew(entity.Id))
    {
        entity.Id = GenerateId();
    }

    if (!Items.Contains(entity))
    {
        Items.Add(entity);
    }

    // ...

    ProcessDependents(entity);

    OnSave(entity);

    return Task.CompletedTask;
}

SaveAsync checks whether the entity has been saved yet. If it hasn't, it generates an Id for it, and then it adds it to the collection. After that there's some stuff for processing dependents (don't worry about that), and an OnSave hook you can override if you want something to happen after the save. If you don't need it, don't use it.

But basically, all it's doing is putting the entity into that collection in memory. And GetByIdAsync just uses LINQ to find it in that same collection.

That's the whole fake.

If even that sounds like more than you want, there's a simpler one in Benday.Common.Testing called InMemoryReadableRepository<T, TKey>. It's a Dictionary and four methods, and the whole file is under fifty lines. The Benday.EfCore.Testing version adds the Id assignment and the call tracking on top of that idea.

Two Saves, One Record

The round trip is nice. The next test is the one a mock really makes you earn: SaveAsync_WhenCalledTwice_UpdatesTheStoredPerson.

[Fact]
public async Task SaveAsync_WhenCalledTwice_UpdatesTheStoredPerson()
{
    // arrange
    var repository = new InMemoryRepository<PersonEntity>();
    var sut = new PersonManager(repository);
    var person = CreateNewPerson();
    await sut.SaveAsync(person);
    var expectedId = person.Id;
    var createDate = person.CreateDate;
    person.Notes = TestConstants.Notes;

    // act
    await sut.SaveAsync(person);

    // assert
    person.Id.ShouldEqual(expectedId, "the second save should keep the Id");
    var stored = repository.Items.ShouldHaveSingleElement("two saves of one person should leave one record");
    stored.Notes.ShouldEqual(TestConstants.Notes, "the update should be stored");
    stored.CreateDate.ShouldEqual(createDate, "CreateDate should not change on an update");
}

Same fake. Create a person, save it, remember the Id and the create date, change the notes, and then save it again.

This is, well, perhaps not the greatest test in the world. But the point is to make sure that when we call save twice on the same person, it behaves the way we'd expect:

  • The Id stays the same. The second save kept the same person instead of treating it as a brand new one.
  • One record in the fake. This time the test keeps a reference to the repository so it can assert against Items directly. Two saves, one element.
  • The update is applied. The stored record has the new notes.
  • CreateDate is untouched. That's real logic in PersonManager: on an update it loads the stored entity first and the stored CreateDate wins over whatever the caller's copy says.

That last one is worth a second look, because of what the second save actually does. PersonManager sees a non-zero Id, calls GetByIdAsync to load the stored entity, copies the changes onto it, and calls SaveAsync again. So the second call has to know about the first one. With the fake, it just does, because the first save really stored something.

Try scripting that with a mock and you're back to building a database out of callbacks.

I ran this one too. It passed in eight milliseconds, with a lot less setup, and no Moq at all.

And it scales in a way the mock setup doesn't. Save a bunch of things in there and you can have a much more complicated starting state without tons and tons of Setup calls.

The Rule: When to Mock, When to Fake

So here's the rule I actually use, in three lines.

Slide: The Rule. Mock when you need an answer you can't produce. Fake when you need state across calls. Verify behavior with a mock, verify data with a fake.

Mock when you need an answer you can't produce for real. Person 2 doesn't exist. The save threw an exception. The clock says nine in the morning. The validator said no.

Fake when the test cares about state across calls. Save then load. Save twice and expect one record. Anything where the second call has to know about the first.

And the short form: verify behavior with a mock, verify data with a fake.

Notice that the Part 3 tests are all still sitting in the same fixture, still using Moq, and I didn't touch them. This isn't a conversion. The mock tests and the fake tests live side by side in PersonManagerFixture, each using the tool that fits.

Moq is not the answer to every test. It's the answer to the tests where you need to lie to the code on purpose.

Recap

  • We tested save-then-load on PersonManager without a single Moq Setup. InMemoryRepository went into the constructor, the fake assigned the Id, stored the entity, and handed it back.
  • We sorted out the two words. A mock is a scripted answer with no memory. A fake is a working implementation with a shortcut.
  • We looked inside the fake: Items is a plain list, SaveAsync assigns the next Id and adds to that list, and GetByIdAsync finds it again. That's the whole trick.
  • The unit test has the same name as the integration test, on purpose. Same test, one with SQL Server and one with a list.
  • We wrote the test a mock makes you earn: two saves of one person, one record in Items, CreateDate untouched.
  • The rule: mock for answers you can't produce, fake for state across calls.

Next time: there's a catch block in PersonManager that nothing in the application can ever reach, and one line of Moq that reaches it.

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: