This is Part 2 of the Mocking with Moq series, the companion to my VSLive 2026 "Mocking with Moq" session.
← Previous: Part 1: Untangle It First
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)
So you've read the overview, Moq is in your test project, and you open up the class to write your first test.
And there's nowhere to put the mock.
The constructor doesn't take anything. Every method creates what it needs with new. Moq can only hand a stand-in to code that asks for one, and this code isn't asking.
So what do you do? You're going to need to do a little refactoring. This post is about the shape your code has to change into before the first test, and nothing else. No Moq syntax today. That's next time.
TL;DR
- Moq builds a stand-in from an interface. A class that creates its own dependencies with
newnever asks for anything, so there's nowhere to put that stand-in. - The fix is one extra habit on top of a well-organized app: a class that needs a collaborator asks for it in the constructor instead of creating it.
- A class that creates its dependency also owns that dependency's dependencies. In this app that's three
news deep, ending at SQL Server. PersonManageris going to depend onIAsyncReadableRepository<PersonEntity, int>: four methods, with no EF Core, no SQL Server and no connection string anywhere in it.PersonEntitymoves to a Common project so Business can see the entity without being able to see the database.- After the change, two things can sit behind that one interface: the real repository in production, and a Moq stand-in in a test.
PersonManagercan't tell them apart.
The App as the Next Demo Opens
Let's start with a quick map of the app.
Coming out of Part 1 there are four projects. There's the console app. There's Business, with Person, PersonManager and the adapter. DataAccess has PersonDbContext and PersonDataAccess. And the unit test project only tests the adapter.
See that arrow from Business to DataAccess? Hold that thought.
Two things got added between episodes, so nobody has to watch them get typed: a Common project that holds PersonEntity, and a SqlPersonRepository sitting in DataAccess, built and unused. Why those two exist is most of this post.
There's also an integration test project that runs PersonManager end to end against a real SQL Server. It's green today, it's slow, and it needs the server up. That's the safety net, and everything the refactoring does has to keep it green.
PersonManager Before
Now let's zoom in on PersonManager, because the shape of it is the whole point today.
PersonManager has two jobs: save a person, and load a person by id. The copying between Person and PersonEntity moved into the adapter back in Part 1. That's pure logic with its own tests, so creating it with new is fine.
Here's the catch. PersonManager creates its own PersonDataAccess with new. Not once. In three different methods. Then PersonDataAccess creates the context, and the context opens a connection to SQL Server.
Here's one of the three:
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;
}
Now look at where every one of those arrows in the diagram goes. Every single one of them points at a concrete class.
Nowhere to Put the Mock
Why does that matter when you sit down to write a test?
Moq builds a stand-in from an interface, but PersonManager doesn't ask for anything. So a test gets the real PersonDataAccess, the real DbContext, and the real SQL Server, every single run. There's nowhere to put the mock.
Another way to say that: there's no way to inject the dependency. And you can't mock your way out of that. The class has to change shape first.
Build It Well (but without Tests)
Let's step back from PersonManager for a second, because I want to be fair to whoever wrote this app.
- The concerns are separated. UI, business logic and data access each live in their own project, and nothing in Business knows how a console app works.
- Every class has one job.
PersonManagercoordinates. The adapter copies fields.PersonDataAccesstalks to SQL Server. You can read each of these classes in one sitting. - It's consistent. Same shape everywhere, same names, same style. The next person can find their way around without a tour.
That's building for maintainability, and this app does all three. It isn't wrong. It's not a bad architecture. It works.
It's just not testable, because it wasn't designed for testability. Whoever wrote it didn't have automated tests as a requirement, so they didn't plan for it. And if you don't plan for it, you don't get it.
That's not bad. It just is.
Build It Well, Plus Testability
Designing for testability is the same list, plus a little extra.
Everything from that list stays exactly where it is. Testability doesn't replace any of it. Same projects, same classes, same jobs.
Then there's one more habit on top: a class that needs a collaborator asks for it in the constructor instead of creating it with new. That's the little extra, and it's the whole difference. Do that, and there's somewhere to put the mock.
Three News Deep
Before we get to the interface, let's look at exactly what this app does instead. Because it isn't one new. It's a chain of them.
It starts in Program.cs, where the console app creates a PersonManager with new. That's the only new in the whole chain that you can actually see from the outside.
Then inside PersonManager, every method creates its own PersonDataAccess. From Program.cs you'd never know it was there.
Then PersonDataAccess creates the PersonDbContext, and the context reads a static connection string and opens SQL Server:
public class PersonDbContext : DbContext
{
// Set once at startup by the console app. Everything that news up a
// PersonDbContext depends on this having been set first.
public static string ConnectionString { get; set; } = string.Empty;
// ...
}
So PersonManager didn't just take on creating PersonDataAccess. It took on everything PersonDataAccess needs, too. Creating a dependency is a concern, and PersonManager now owns that concern three levels deep.
Here's why that matters beyond testing. That connection string is a static, and it defaults to empty. If nobody sets it, EF Core throws on the first query, three boxes deep. Now look at the stack trace. There's an inner exception down in EF Core, but the first line of your code in that trace is PersonManager.LoadByIdAsync.
The exception says PersonManager. And PersonManager never asked to own any of that.
Who Creates the Dependency?
That chain is the difference between two ways of thinking, and it comes down to one question. Who creates the dependency?
Without dependency injection, the class creates it. Creating the dependency is PersonManager's job. And it's not just the one dependency. It's the context, and the connection string, and whatever those need next year. Every one of them becomes PersonManager's problem. When creating one of them fails, the real cause is buried in an inner exception and the trace points at your class.
With dependency injection, the class asks for it. The class says this:
I don't create my dependencies. You create them, you hand them to me, and what I need is advertised right on the constructor.
Creating the dependency moves out of the class, and scope and lifetime go with it. Today that's Program.cs, and later it's a DI container, but it's the same idea either way. And if the connection string is missing, Program.cs catches that at startup, before PersonManager even exists. Nothing bubbles up through your class, and the exception says what actually went wrong.
That's dependency injection. The habit that comes with it is basically an allergy to the new keyword, for anything that has dependencies of its own.
The adapter doesn't have any, so creating it with new is fine, and it stays. PersonDataAccess drags a context and a connection string in behind it, so it goes.
The Repository Interfaces
So the shape PersonManager is going to change into is "asks for an interface". Here's what that interface actually is.
These come from my Benday.Common library, in the Benday.Common.Interfaces namespace. Trimmed down to the signatures, they look like this:
public interface IAsyncRepository<T, TKey>
where T : IEntityIdentity<TKey>
where TKey : IEquatable<TKey>
{
Task SaveAsync(T entity);
Task DeleteAsync(T entity);
}
public interface IAsyncReadableRepository<T, TKey>
: IAsyncRepository<T, TKey>
where T : IEntityIdentity<TKey>
where TKey : IEquatable<TKey>
{
Task<T?> GetByIdAsync(TKey id);
Task<IList<T>> GetAllAsync();
}
The base one is IAsyncRepository, and it's just the write side: SaveAsync and DeleteAsync. Then IAsyncReadableRepository inherits from it and adds the two reads, GetByIdAsync and GetAllAsync. That's the one PersonManager is going to depend on, because it both saves and loads.
The constraint on T is IEntityIdentity<TKey>, which just says the entity has an Id of type TKey. For PersonEntity against SQL Server, TKey is int.
So that's four methods, with no EF Core, no SQL Server, and no connection string anywhere in it. That's what makes it mockable.
If you'd rather write your own four-method interface, that works exactly the same way. I use the library interface instead of writing my own IPersonRepository because it pays off later in the series.
The Real One Is Six Lines
The real implementation of that interface is SqlPersonRepository, and here's the entire class:
public class SqlPersonRepository : EfCoreCrudRepositoryBase<PersonEntity, PersonDbContext>
{
public SqlPersonRepository(PersonDbContext context) : base(context)
{
}
protected override DbSet<PersonEntity> EntityDbSet => Context.Persons;
}
It derives from EfCoreCrudRepositoryBase, from my Benday.EfCore library, and that base class already implements IAsyncReadableRepository. All four methods live up there.
The constructor takes the PersonDbContext instead of creating one. That's the same idea we're about to apply to PersonManager, one level down.
And the one override says which DbSet to use. That's the whole class, and honestly, that's the reason I bother maintaining a library.
(If you're on Cosmos DB instead of SQL Server, Benday.CosmosDb has the same patterns.)
Why PersonEntity Moves to Common
PersonManager is about to depend on a repository of PersonEntity, so Business has to be able to see PersonEntity.
And I know what you're going to say. Just leave the entity in DataAccess and reference it from Business. It's one line in the csproj.
Here's the trouble with that idea. If Business can see DataAccess, then anything that references Business, including your unit test project, can reach PersonDbContext and SQL Server. The arrow is still there. It's just longer.
So PersonEntity moves into Common. Business references Common, DataAccess references Common, and once PersonManager stops using PersonDataAccess, neither one references the other. Now the unit test project can't reach SQL Server even if it tries, because there's no arrow to follow.
Moving the entity is just a file move and a namespace. But it isn't tidiness. It's what stops a unit test from reaching SQL Server by accident.
PersonManager Before and After
You saw the before version of LoadByIdAsync up above: no constructor, so nothing comes in from the outside, and the method creates its own PersonDataAccess and then uses it.
Here's the after:
public class PersonManager
{
private readonly IAsyncReadableRepository<PersonEntity, int> _repository;
// ...
public PersonManager(IAsyncReadableRepository<PersonEntity, int> repository)
{
_repository = repository;
}
// ...
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;
}
}
The constructor asks for the readable repository and stores it in a field. Every method uses the field instead of creating anything. PersonDataAccess isn't mentioned in here anymore. The other two methods get the same treatment.
And no, there's no second parameterless constructor to keep the build green, and no null check. The parameter type is the contract, and the compiler enforces it at every call site. You'll see why that matters next time.
So who does the creating now? The place that starts the app up:
// The real dependency: SQL Server.
var manager = new PersonManager(new SqlPersonRepository(new PersonDbContext()));
That's Program.cs. All three news, out in the open, on one line.
One honest caveat: the logger and the clock are still created inline in PersonManager. They each get their own episode.
Two Things, One Interface
Here's the picture to keep in your head for the rest of the series.
PersonManager points at the interface now, not at a class. In production, the thing injected through the constructor is SqlPersonRepository: EF Core talking to SQL Server.
In a unit test, the constructor gets a stand-in that Moq builds from the interface at runtime. PersonManager can't tell the two apart, and that's the entire trick. (The syntax is in the overview, so I won't repeat it here.)
A test can get in anywhere an arrow points at an interface. Arrows at concrete classes are closed doors.
Later in the series, a third thing joins this picture, and it isn't a mock.
Recap
- Nowhere to put the mock. Moq builds a stand-in from an interface. A class that creates its own dependencies never asks for one, and you can't mock your way out of that.
- The app isn't bad. It's separated, focused and consistent. It just wasn't designed for testability, and if you don't plan for it, you don't get it.
- Ask, don't create. Dependencies arrive via the constructor. Be allergic to
newfor anything that has dependencies of its own. - Creating a dependency is a concern. It moves out of the class and into the place that starts the app:
Program.cstoday, a container later. - The interface is four methods.
IAsyncReadableRepository<PersonEntity, int>, with no EF Core and no SQL Server in it.SqlPersonRepositoryis the real one, in six lines. - The entity moves to Common so that Business, and the unit tests behind it, have no arrow to follow into the database.
That's the shape change, and that's enough slides. Part 3 actually implements it: add that constructor, let the build break on purpose so the compiler points straight at the two places that need the real repository handed in, then write the first unit test with a mock, watch it fail, refactor PersonManager onto the repository, and watch it go green. And we find a real bug on the way.
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
- Start here: What Is Moq, and Why Would I Mock Anything?
- Part 1: How Do I Unit Test Code That Calls the Database? Untangle It First
- Part 2: How Do I Make My Code Mockable? (you are here)
- Part 3: How Do I Unit Test Code That Calls the Database? Mock the Repository
More coming soon.
Related:
- Demo code on GitHub: before and after for every episode
- The Mocking with Moq playlist on YouTube
- Moq on GitHub
- Benday.Common on GitHub:
IAsyncReadableRepositoryand the other repository interfaces - Benday.EfCore on GitHub:
EfCoreCrudRepositoryBase, used in this sample - Benday.CosmosDb on GitHub (the same patterns for Azure Cosmos DB) and Benday.AzureStorage on GitHub (the blob storage bridge for cloud apps)