模拟DbContext.set <t> .Add()EF6 </t>

时间:2014-06-24 19:56:30

标签: c# .net entity-framework unit-testing moq

我有以下类(其中PilsnerContext是DbContext类):

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){}

}

我正在尝试对Add方法进行单元测试,模拟上下文,如:

[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);
    }
}

但断言:

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

失败了,我假设是因为我在Add方法中使用了Context.set()。Add()而不是Context.Prospects.Add()但是通过这个测试的正确方法是什么?

例外是:

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

提前致谢。

2 个答案:

答案 0 :(得分:20)

您似乎错过了设置以返回DbSet

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

答案 1 :(得分:5)

我尝试了你的解决方案Patrick Quirk,但我收到一个错误,告诉我DbContext.Set不是虚拟的。

我在这里找到了解决方案:

How to mock Entity Framework 6 Async methods?

创建DbContext的接口,如

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

这样我可以嘲笑它。

谢谢!

这是我的第一个问题btw,我不确定我是否可以将此问题标记为重复或其他内容。