What Is Moq, and Why Would I Mock Anything? | Mocking with Moq

November 19, 2026
What Is Moq, and Why Would I Mock Anything? | Mocking with Moq

This is the overview episode of the Mocking with Moq series, the companion to my VSLive 2026 "Mocking with Moq" session.

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)

Raise your hand if you've ever written a unit test that needed the database to be up. Keep it up if that test ever failed for a reason that had nothing to do with your code.

Yeah. That's probably most of us.

Moq as a framework, and mocking as a technique, is how you get away from that problem. This post is the why and the syntax in one place, before the rest of the series puts it to work. The second half is meant to be a reference page: one Moq move per section, with real code from the demo repo.

TL;DR

  • A test is an experiment. If you can't hold the dependencies still, you can't tell what made it fail.
  • If your class creates its own dependencies, your test has no control over them. Hand them in from the outside and the test decides what each one is.
  • Moq starts with a C# interface and generates a stand-in for a collaborator at runtime. It helps you test in isolation.
  • There are five testing problems in this series (infrastructure, exceptions you can't trigger, interactions, data scenarios, and "not my circus"), and there's a Moq move for each.
  • The moves: Mock<T> and .Object, Setup with Returns / ReturnsAsync, It.IsAny and It.Is, Callback, ThrowsAsync, Verify with Times.Once and Times.Never.
  • A Loose mock returns the default for anything you didn't set up, so a bool comes back false. That's a trap, not a bug.

A Test Is an Experiment

You've probably written unit tests before, maybe so many that it's second nature. So let's look at it with fresh eyes and borrow the scientific method.

Slide: A Test Is an Experiment. Hypothesis, experiment, and results. Green confirms the hypothesis. Red means go find out why. Change one thing, hold the rest still.

A test is a hypothesis: if I call this method with these inputs, I expect that result. It's also the experiment and the gathering of the results, all in one little method.

When the test passes, it confirms your hypothesis and you get to move on with your day. When it fails, and you really think it should have worked, now you've got to figure out why.

The way you do that in any experiment is you change one thing at a time and hold everything else constant. That way, when the result changes, you know the one thing you touched is the thing that did it.

Who Controls the Variables?

Now think about how a lot of our automated tests are actually built. The class you're testing almost never works alone. It needs other things in order to run, and every one of those is another variable in your experiment. We call those things dependencies, or collaborators, and the question is whether your test has any control over them.

The class in this series is called PersonManager, and it needs data access, a logger, and the clock.

In the bad version, it creates all three for itself. They're locked inside the box. Your test can't reach in there, which means it can't hold any of them still. You get the real database and the real time of day, every single run.

Slide: Who Controls the Variables? A diagram of PersonManager pointing at three collaborators outside itself: data access (SQL Server), logger, and clock. Inside the box: no control. Outside the box: yours to control.

In the good version, those three collaborators are on the outside. PersonManager doesn't create them anymore. It just gets handed them. So now your test decides what each one is, and it can hold all three constant and change only the thing it's asking about.

Moq in One Sentence

That's the experiment we want to run, and Moq is the tool that makes it happen:

Moq is a library that starts with a C# interface and generates a stand-in for one of your collaborators on the fly at runtime.

Plus it has a bunch of functionality to simulate logic, simulate errors, and verify the interactions between your code and those stand-ins. In short, it helps you test in isolation.

The Airplane Bathroom Problem

OK, so now we need to talk about airplane bathroom door latches.

Slide: The Airplane Bathroom Problem. Somewhere, there's a test plan for this latch. A photo of the sliding lock on an airplane bathroom door.

That's the latch on an airplane bathroom door. I would be surprised, honestly amazed, if there weren't a test plan for that latch in a binder somewhere. So let's think about what that test plan has in it. I'm going to bet it says something like this.

Slide: The Latch Test Plan. Install the door and the latch. Gas up the plane and take off. Climb to 40,000 feet. Wiggle the latch. Land, then turn the page.
  1. Install the door and the latch on the plane.
  2. Gas up the plane, taxi out, and take off.
  3. Climb to forty thousand feet. The pilot calls back to the testing team to say they're ready.
  4. Walk to the door and wiggle the latch. If it properly locks and unlocks, record the result.
  5. Land the plane, turn the page in the manual, and move on to the next thing in the list of stuff to test.

And it turns out the next thing to test is the landing gear retraction and deployment thingy.

Slide: The Landing Gear Test Plan. Take off, retract the gear. Climb to 40,000 feet. Land the plane. Deploy the gear on final approach. Gear deploys? Pass. Gear fails? Crash.

So they top up the fuel tank, take the plane back up, and retract the landing gear. They keep on flying up to forty thousand feet, because that's what the test needs. But this test is about deploying the gear, so they're not done yet. The setup they need is to land the plane. They loop back around, get into the approach pattern, and on final approach they deploy the landing gear. This is the whole point of the test.

If the gear deploys, the test passes. If the gear fails to deploy? Well, they crash. But a result is a result, right?

It's all totally 100% reasonable.

Test Systems in Isolation

Does either one of those sound reasonable to you? No, of course not. In both plans you took the whole plane up to check one part.

There's a better way, and it's testing systems in isolation. The latch gets tested on a bench. The landing gear gets tested on the ground, probably in some kind of specialized test rig, or maybe in a hangar with a plane up on jacks. That's a lot less setup and about a zillion fewer dependencies baked into the test.

Your Service Class Is the Landing Gear

Here's the turn. Your service class, the one that calls SQL Server? That's the landing gear.

Every unit test that needs the database up, the network up, and the clock to say Tuesday is a test flight. It's slow, it's flaky, and when it fails you don't know whether your code broke or the infrastructure did.

Mocking is how you put that class on the bench.

Put the Collaborators on the Bench

Back to PersonManager, because that's the class this whole series tests, and all it really does is save people. It talks to three things: a repository that hits SQL Server, a logger, and the clock. Those three come in through the constructor, which is all the dependency injection I'm going to cover here. The rest of that story is Part 2: How Do I Make My Code Mockable?.

Slide: Put the Collaborators on the Bench. A diagram of PersonManager pointing at a mock repository, a mock logger, and a mock clock. PersonManager has three collaborators. Swap all three for stand-ins.

In a unit test, we swap all three for stand-ins. Now the only real code running is PersonManager, so the only thing that can fail is PersonManager. That's the whole idea. Everything after this is just the syntax for it.

Five Testing Problems

So where does isolation actually pay off? Here are the five testing problems this series solves, with the Moq move for each.

Slide: Five Testing Problems. Infrastructure: it needs SQL Server. Exception handling: errors you can't trigger. Interactions: did it call the right stuff? Data scenarios: what time is it? Not my circus: validation is the validator's job.
The problem What it looks like The Moq move
Infrastructure Your class needs something slow or heavy, like a repository that's useless without SQL Server Setup and ReturnsAsync
Exception handling SQL Server running out of disk space is a real failure, but good luck making it happen on demand ThrowsAsync
Interactions The requirement isn't a return value, it's whether your class called the right thing. Did that error get logged? Verify
Data scenarios You need one specific answer from a dependency, like a particular time of day Returns on a TimeProvider
Not my circus PersonManager's tests shouldn't have to understand all the validation rules for a Person A mock validator that says valid or not valid

That last one is "not my circus, not my monkeys." The validation rules are a different problem for a different test, against the PersonValidator class. When you're testing PersonManager, you just need a simple answer: valid or not valid.

Those five problems are the series. The rest of this post is the syntax for all of it, in the order a test needs it.

The Moq Syntax Reference

Mock<T> and .Object

Every mock has two halves.

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();

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

    // TimeProvider is an abstract class, and its GetUtcNow() is virtual, so Moq can fake it.
    private Mock<TimeProvider> Clock => field ??= new();

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

    // ...
}

It's one Mock<T> per constructor parameter, and Mock<T> is the remote control. It's what your test configures, and what it asks questions of later.

That field ??= new() just means "create it the first time a test touches it," so every test gets fresh mocks.

Then .Object is the actual stand-in, and that's what PersonManager receives. If you've ever passed the mock itself to a constructor and gotten a compile error, you forgot .Object. Welcome to the club.

Setup and ReturnsAsync

Next, make the stand-in actually answer a question.

// arrange
Repository.Setup(x => x.GetByIdAsync(1)).ReturnsAsync(CreateExistingEntity());

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

Setup says which call you care about, and you write it as a lambda, because that's what Moq is built around. ReturnsAsync says what to hand back. So that line reads: when somebody asks for person one, answer with this entity. No database, no connection string.

The same move with a different answer gives you the not-found case:

Repository.Setup(x => x.GetByIdAsync(2)).ReturnsAsync((PersonEntity?)null);

Gotcha: it's Returns for a plain method and ReturnsAsync for anything that returns a Task. Mixing those up is compile error number two.

It.IsAny and It.Is

That setup matched on person one exactly. Usually you want to be looser than that, or pickier.

It.IsAny<T>() means "I don't care which argument you were called with, treat them all the same":

Repository.Setup(x => x.SaveAsync(It.IsAny<PersonEntity>())).ThrowsAsync(expected);

It.Is<T>() takes a lambda, so the setup only matches when the argument passes your test. That's where a rule about the input goes. This is the one from the slide:

// only ids that pass this test
Repository.Setup(x => x.GetByIdAsync(It.Is<int>(id => id > 0)))
    .ReturnsAsync(CreateExistingEntity());

And when the argument is the requirement, you just pass the exact thing. This checks that this exception got logged, not just any exception:

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

Gotcha: the one I see the most is It.IsAny on everything, so the test passes even when the code emails the wrong customer. Put the business rule in the matcher.

Callback

Sometimes you don't want the mock to answer. You want to see what it was handed. That's Callback.

// 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");

Callback runs a bit of your own code when the mock gets called, and the argument comes along. Here we just stash the entity so the test can look at it.

Or the callback can play the database. SQL Server assigns the Id on a save, so the callback stamps a 42 on the entity, and the test checks that it got copied back onto the Person:

// arrange
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");

Gotcha: on a method that returns a value, Callback doesn't replace Returns. You still need both.

Returns: Pin the Clock

The most common untestable dependency in business code is the clock, so let's pin it. We stop asking the real clock. The fixture defines one fixed moment called Now, and Setup plus Returns pins GetUtcNow to it.

private static readonly DateTimeOffset Now = new(2026, 11, 17, 9, 0, 0, TimeSpan.Zero);

// ...

Clock.Setup(x => x.GetUtcNow()).Returns(Now);

Now the test can assert the exact timestamp, and nothing fails only at midnight.

If the thing you're pinning is a property instead of a method, the move is SetupGet, with the same Returns on the end. From the slide:

// a property gets SetupGet instead
Clock.SetupGet(x => x.LocalTimeZone).Returns(TimeZoneInfo.Utc);

Or skip the mock entirely, because Microsoft ships FakeTimeProvider, a fake clock you can move forward with Advance:

// arrange
var clock = new FakeTimeProvider(Now);
var sut = new PersonManager(new InMemoryRepository<PersonEntity>(), Logger.Object, clock);
var person = CreateNewPerson();
await sut.SaveAsync(person);

// act
clock.Advance(TimeSpan.FromHours(1));
await sut.SaveAsync(person);

// assert
person.CreateDate.ShouldEqual(Now.UtcDateTime, "CreateDate should stay at the first save");
person.LastModified.ShouldEqual(Now.UtcDateTime.AddHours(1), "LastModified should follow the clock");

Gotcha: this all works because TimeProvider is abstract and GetUtcNow is virtual. DateTime.Now has no seam at all.

ThrowsAsync

This one's my favorite. PersonManager has a catch block for SQL Server running out of disk space, and nothing in the app can ever throw that.

// 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");

That one ThrowsAsync line is the utility that starts SQL Server and fills the disk with garbage. And the test takes about four milliseconds.

Then xUnit's Assert.ThrowsAsync runs SaveAsync, and it only passes if that exception type comes back out. It hands you the exception, too.

Then you assert whatever the business said should happen. Here the rule is that the original exception comes back out, not a wrapped copy. That's why it's in a variable.

Verify, Times.Once, Times.Never

Everything so far was about what the mock says. Verify is about what the mock heard.

// were you called with this exact exception, exactly once?
Logger.Verify(x => x.WriteToLog(expected), Times.Once);

// were you ever called? You'd better not have been.
Logger.Verify(x => x.WriteToLog(It.IsAny<Exception>()), Times.Never);

// the happy path saved through the repository
Repository.Verify(x => x.SaveAsync(It.IsAny<PersonEntity>()), Times.Once);

Verify asks the stand-in a question after the fact: were you called with this exact exception, exactly once? That's a business rule written as a test.

Times.Never proves something did not happen, which is surprisingly hard to prove any other way. A good save shouldn't log an error, and this is the verify most people forget exists.

Gotcha: I know you're going to want to verify every single call, because it feels thorough. Please don't. Then your test is a second copy of your implementation, and every refactor breaks ten tests without a single bug. Verify the calls that are the requirement.

Loose vs Strict

This one's not a move, it's a setting. And it's the thing that makes people give up on mocking.

Slide: Loose vs Strict. Loose (the default): unconfigured calls return default, bool is false and Task is completed, the default might be the unhappy path. Strict: unconfigured calls throw, the exception names the call, then switch it back.

Loose is what you get when you don't say anything. On a Loose mock, any call you didn't set up just quietly returns the default for its type. A bool comes back false, a Task comes back already completed, and a reference type comes back null.

That's a trap you'll hit later in the series. The validator's IsValid returns false, so every person is invalid and every save goes red. The fix is one Setup that defaults it to true:

field = new Mock<IValidatorStrategy<Person>>();
field.Setup(x => x.IsValid(It.IsAny<Person>())).Returns(true);

Strict is what you turn on with MockBehavior.Strict. On a Strict mock, any call you didn't set up throws instead. And the exception names the exact call nobody set up, which is why I flip a mock to Strict for a minute whenever it isn't doing what I expect.

Now I know what you're thinking: why not always use Strict? Because then every test sets up every call it doesn't care about, and you're writing your implementation twice. So Strict for a minute, Loose for the rest.

Mocking a Class, Not an Interface

Everything so far mocked an interface (or an abstract class, in TimeProvider's case). Moq can also mock a concrete class, and that's where the legacy code tools live.

// A mock of a concrete class. It works because PersonDataAccess's methods are virtual.
private Mock<PersonDataAccess> DataAccess => field ??= new Mock<PersonDataAccess>();

// ...

// CallBase = true: run PersonManager's real code unless a member is overridden.
field = new Mock<PersonManager> { CallBase = true };

// Override the protected CreateDataAccess() seam by name (it's protected, so a
// lambda can't reach it). Now every PersonDataAccess the real code asks for is the mock.
field.Protected()
    .Setup<PersonDataAccess>("CreateDataAccess")
    .Returns(DataAccess.Object);

Moq can stand in for a class, but it can only intercept the members it can override, which means virtual and abstract ones. Everything else runs the real code.

CallBase = true says "run the real class for everything except what I override." That's a partial mock, and it's how you get a first test around a class that creates its own dependencies.

Protected() gets you at a protected member by its name as a string, because a lambda can't see it.

None of the numbered episodes needs this. It's here so you've seen it. That snippet comes from the refactoring folder in the demo repo, and the two refactoring videos after the series are where it earns its keep.

What Moq Can't Do

One section on the limits, because every one of these is a real question I get.

Slide: What Moq Can't Do. Static methods. Anything the class creates with new. Sealed classes, non-virtual members. Find the seam, or make one.
  • Static methods. There's nothing to override. DateTime.Now is the famous one.
  • Anything your class creates for itself with new. There's no way for a test to get in between.
  • Sealed classes and non-virtual members. Same reason. If Moq can't override it, it can't stand in for it.

So find the seam, or make one. For the clock, .NET already made the seam, and it's called TimeProvider. For everything else, wrap it in a small interface you own, and mock that instead.

Recap

  • A test is an experiment. Change one thing, hold the rest still. You can only hold still the dependencies you control.
  • Your service class is the landing gear. A test that needs the database is a test flight. Mocking puts the class on the bench so the only thing that can fail is that class.
  • Mock<T> is the remote control, .Object is the stand-in. Setup picks the call, and Returns, ReturnsAsync or ThrowsAsync picks the answer.
  • It.IsAny when you don't care, It.Is or the exact value when you do. Callback when you want to see what the mock was handed.
  • Verify the requirement, not every call. And remember Times.Never exists.
  • Loose is the default, and the default might be the unhappy path. Flip to Strict for a minute when a mock isn't doing what you expect.

Every move here shows up in the series at the exact moment a test needs it, with a reason, and usually with a red test run first. All of the code is on GitHub, and every episode has a before folder and an after folder so you can type along. Next up is Part 1, where we start untangling code that calls the database. Go put something on the bench.

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: