【问题标题】:Typemock Isolator: How to mock a DbContext that is not injected?Typemock Isolator:如何模拟未注入的 DbContext?
【发布时间】:2017-08-04 02:47:43
【问题描述】:

我正在一个 Asp.Net MVC 项目中测试我的存储库,我需要为我的单元测试模拟一个 DbContext。 DbContext 没有注入,我无法更改代码。

我检查了这个answer 并一步一步地跟着它,但它没有用。这是我的代码,我试图简化它:

    [TestMethod]
    public void SaveAmountsAfterCalculation()
    {
        // Faking the Context
        var fakeContext = Isolate.Fake.NextInstance<MyContext>();
        Isolate.WhenCalled(() => new MyContext()).WillReturn(fakeContext);

        // Faking one the the DbSetList of the Context
        Isolate.WhenCalled(() => fakeContext.SomeDbSet)
        .WillReturnCollectionValuesOf(somehtingElseList);

        // Calling the method to test
        MyRepository.SaveAmountsAfterCalculation();

        // Verifying if SomeProperty was called
        Isolate.Verify.WasCalledWithAnyArguments(() => fakeContext
        .SomeProperty.Attach(null));
    }

在 using 语句中创建上下文时,不会抛出异常。

using (var ctx = new MyContext())
{
   ...
   // The exception is thrown here.
   if (ctx.SomeDbSet.Any(...))
   ...
}

但如果我检查任何属性 (DbSet),则会看到以下错误:在应用程序配置文件中找不到名为“MyContext”的连接字符串。。我已经在我的测试项目中添加了一个连接字符串,但它也不起作用。在调用SomeDbSet 的那一刻,即使我告诉TypeMock 用somethingElse 替换该方法的结果,也会引发异常。见上面的代码。

【问题讨论】:

  • Luis 你能发布你的完整测试和被测方法吗?没有它很难理解问题是什么。
  • 它完成了@JamesR!
  • 你的例子不是很清楚,首先你没有提供你测试的方法实现(SaveAmountsAfterCalculation)所以很难理解你在测试什么,其次是属性SomeProperty 也未显示。请提供更详细的示例,以便我们尝试帮助您。

标签: c# entity-framework unit-testing dependency-injection typemock-isolator


【解决方案1】:

看起来"Isolate.WhenCalled(() =&gt; new MyContext()).WillReturn(fakeContext);" 行已过时,可能会导致您的问题,因为您在使用 fakeNextInstance 时已经伪造了调用 "new MyContext()"

【讨论】:

  • 什么是 somehtingElse 实例?
  • 这是一个列表。为简单起见,我没有使用我的真实姓名。
猜你喜欢
  • 1970-01-01
  • 2011-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-30
  • 2011-11-30
  • 1970-01-01
相关资源
最近更新 更多