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.
It looks like you're just missing the setup to return your DbSet
:
mockContext.Setup(m => m.Set<Prospect>()).Returns(mockProspect.Object);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With