简体   繁体   English

Moq模拟的DbContext返回null

[英]Moq mocked DbContext returns null ObjectContext

I have a custom DisconnectedDbContext for use with self state tracking POCOs in a web app. 我有一个自定义DisconnectedDbContext用于Web应用程序中的自我状态跟踪POCO。

public abstract class DisconnectedDbContext : DbContext
{
    protected DisconnectedDbContext()
    {
        var objAdapterContext = ((IObjectContextAdapter)this).ObjectContext;
    }
}

I subclass this for some unit testing: 我将其细分为一些单元测试:

public class FruityContext : DisconnectedDbContext
{
    public virtual DbSet<FruitBowl> FruitBowls { get; set; }
    public virtual DbSet<Fruit> Fruits { get; set; }
}

And using Moq in a TestMethod as below: 并在TestMethod使用Moq ,如下所示:

[TestMethod]
public void CreateAFruityContext()
{
    var dbc = new FruityContext();
    Assert.IsNotNull(dbc);
    var mockSet = new Mock<DbSet<FruitBowl>>();
    var mockContext = new Mock<FruityContext>();
    mockContext.Setup(m => m.FruitBowls).Returns(mockSet.Object);
    var mo = mockContext.Object;
    Assert.IsNotNull(mo);
}

Now this is not an actual TestMethod so I don't want to get sidetracked about that. 现在这不是一个实际的TestMethod所以我不想为此而烦恼。

My problem is that for the creation of var dbc in this method, objAdapterContext in the constructor call is not null however for var mo it is null. 我的问题是,在此方法中创建var dbc时,构造函数调用中的objAdapterContext不为null,但对于var mo则为null。 I need objAdapterContext to be not null, as per non-mocked objects because I tap into this to handle the ObjectMaterialized event of the ObjectContext . 对于非模拟对象,我需要objAdapterContext不为null,因为我可以使用它来处理ObjectContextObjectMaterialized事件。

So the Moq wrapper is changing the behaviour of my code. 因此,Moq包装器正在改变我的代码的行为。 Is there something I can do about this? 有什么我可以做的吗?

Use this: 用这个:

mockSet.CallBase = true;
mockContext.CallBase = true;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM