Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock DbContext.set<T>.Add() EF6

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);
        Context.SaveChanges();
        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:

[TestClass]
public class ProspectTest
{
    [TestMethod]
    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
        };

        prospectService.Add(newProspect);

        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.

like image 831
ferflores Avatar asked Jun 24 '14 19:06

ferflores


2 Answers

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

mockContext.Setup(m => m.Set<Prospect>()).Returns(mockProspect.Object);
like image 165
Patrick Quirk Avatar answered Nov 15 '22 12:11

Patrick Quirk


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.

Thanks!

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

like image 23
ferflores Avatar answered Nov 15 '22 10:11

ferflores