Mock DbContext.set.Add() EF6

.net c# entity-framework moq unit-testing


I have the following classes (where PilsnerContext is a DbContext class):

public abstract class ServiceBase<T> : IService<T> where T: class, IEntity
    protected readonly PilsnerContext Context;

    protected ServiceBase(PilsnerContext context)
        Context = context;

    public virtual T Add(T entity)
        var newEntity = Context.Set<T>().Add(entity);
        return newEntity;

public class ProspectsService : ServiceBase<Prospect>
    public ProspectsService(PilsnerContext context) : base(context){}


And i'm trying to make a unit test of the Add method mocking the context like:

public class ProspectTest
    public void AddProspect()
        var mockProspect = new Mock<DbSet<Prospect>>();
        var mockContext = new Mock<PilsnerContext>();

        mockContext.Setup(m => m.Prospects).Returns(mockProspect.Object);

        var prospectService = new ProspectsService(mockContext.Object);

        var newProspect = new Prospect()
            CreatedOn = DateTimeOffset.Now,
            Browser = "IE",
            Number = "1234567890",
            Visits = 0,
            LastVisitedOn = DateTimeOffset.Now


        mockProspect.Verify(m=>m.Add(It.IsAny<Prospect>()), Times.Once);
        mockContext.Verify(m=>m.SaveChanges(), Times.Once);

But the assert:

mockProspect.Verify(m=>m.Add(It.IsAny<Prospect>()), Times.Once);

Is failing, I assume is because I'm using Context.set().Add() instead of Context.Prospects.Add() in the Add method but how is the correct way to pass this test?

The exception is:

Expected invocation on the mock once, but was 0 times: m => m.Add(It.IsAny<Prospect>()) No setups configured. No invocations performed.

Thanks in advance.

6/24/2014 8:06:53 PM

Accepted Answer

I tried your solution Patrick Quirk but I was getting an error telling me that DbContext.Set is not virtual.

I found the solution for that here:

How to mock Entity Framework 6 Async methods?

Creating an interface of the DbContext like

    public interface IPilsnerContext
       DbSet<T> Set<T>() where T : class;

That way I could mock it.


This is my first question btw, I'm not sure if I can mark this question as duplicated or something.

5/23/2017 12:25:39 PM

Popular Answer

It looks like you're just missing the setup to return your DbSet:

mockContext.Setup(m => m.Set<Prospect>()).Returns(mockProspect.Object);

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow