【问题标题】:Mocking with Entity Framework and TypeMock使用实体框架和 TypeMock 进行模拟
【发布时间】:2016-09-09 17:02:48
【问题描述】:

当谈到 EF(第 6 版,就它的价值而言)时,我在模拟方面遇到了真正的问题。

这是我正在尝试测试的方法:

    public async Task<bool> IsSurveyComplete(Guid entityRef)
    {
        using (MyDbEntities context = new MyDbEntities())
        {
            MyEntity entity = await context.MyEntities.FindAsync(entityRef);
            // do stuff
        }
    }

我需要伪造“实体”,但我意识到仅仅尝试做 Isolate.Fake.Instance 是行不通的,因为它实际上是一个 ObjectProxy 而不是 MyEntity 类型的实例。我发现解决这个问题的方法是将 context.Configuration.ProxyCreationEnabled 设置为 false。 但是,如果我在构造函数之外的任何地方执行此操作,这将不起作用。如果我尝试伪造 DbContextConfiguration,它仍然使用代理。

所以,我创建了一个新的构造函数供测试时使用:

    public MyDbEntities(bool useProxy)
        : base("name=MyDbEntities")
    {
        this.Configuration.ProxyCreationEnabled = useProxy;
    }

然后,在我的测试中:

    Isolate.WhenCalled(() => new MyDbEntities()).WillReturn(new MyDbEntities(false));

但是,当我在 using 语句之后的 IsSurveyComplete 方法中放置断点时,ProxyCreationEnabled 属性仍然设置为 true。

我也尝试过(在许多其他方面):

    var fakeContext = new MyDbEntities(false);
    Isolate.Swap.AllInstances<MyDbEntities>().With(fakeContext);

同样,当我使用断点进行调查时,ProxyCreationEnabled 为真。

我要放弃TypeMock了!

【问题讨论】:

  • 你能上传你的“IsSurveyComplete”代码和你的测试吗?

标签: mocking entity-framework-6 typemock typemock-isolator


【解决方案1】:

声明者:我在 typemock 工作

你使用了错误的typemock函数,你应该使用:

var fakeContext = Isolate.fake.NextInstance<MyDbEntities>();
Isolate.whenCalled(()=>fakeContext.MyEntities).
   WillReturnCollectionValuesOf(listOfEntities.AsQueryable());

代替:

var fakeContext = new MyDbEntities(false); Isolate.Swap.AllInstances<MyDbEntities>().With(fakeContext);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多