c# - 如何在 Nunit Framework 的 Autofac 容器中更新已注册类的属性

标签 c# unit-testing dependency-injection nunit autofac

我在 NUnit 中使用依赖注入(inject)框架 AutoFac ,如所述 here

这些类被注册为 SingleInstance 范围。

其中一个类依赖于 Setting 类,如下所示:

    class Product
    {
       public (Setting setting, Dep1 dependency) {....   }
       ....
     }

我想更新每个测试用例的“设置”类之一的属性。

 [Test]
 public void Test()
 {

  //Arrange
  var setting = Resolve<Setting>
  Setting.Id = value
  // product depend on two dependency injected via constructor
  var product = Resolve<Product> ; 

  //the problem is: the new values of setting class are not reflected in 
   //Product, and the Product still use the default values provided by the container

    ......        

  }

问题是更新后的值没有反射(reflect)在容器中,单元测试失败,Product 类仍然使用默认值

我尝试使用 this solution , 但它无济于事。 AutoFac 的文档不要提供在 NUnit 或测试套件中使用的指南。

问题:如何更新类 setting 的值并将新值自动注入(inject)到 product 类的构造函数中在 NUnit 中?

最佳答案

简短的回答

你不知道。

长答案

每个应用程序都应该有自己的 Composition Root .由于测试项目是独立于被测类的应用程序,因此您会 never share a production configuration with a test configuration .

进行单元测试时,您通常不会一次处理超过六个左右的依赖项。为此目的设置 DI 容器是不切实际的。相反,您应该新建被测类并模拟除 DTO 和模型对象之外的所有其他内容。

[Test]
public void Test()
{
    var setting = new Setting { Value1 = "x", Value2 = "y" };
    var dep1 = new Mock<Dep1>();
    // setup Moq conditions on dep1

    var product = new Product(setting, dep1);

    // Execute method on product and assert
}

集成测试时,也最好使用pure DI而不是为了测试目的而设置 DI 容器。但是,如果您确实使用 DI 容器,它应该有自己的配置,与被测试的应用程序分开。即使这不被认为是一种不好的做法,仍然会有需要模拟的依赖项来保证这一点。您不是在测试 DI 容器配置,而是在测试应用程序的组件,因此没有必要让它们完全相同。

NOTE: It is strongly advised to use abstractions rather than concrete types as constructor parameters. The usual route is to use interfaces (although I would argue that "settings" might not need to be), but abstract classes will also work.

关于c# - 如何在 Nunit Framework 的 Autofac 容器中更新已注册类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48411964/

相关文章:

c# - IntelliLock 的许可证文件 (license.license) 不工作

c++ - 如何在 C++ 中使用 gtest/gmock 为调用另一个全局函数的全局函数编写单元测试?

node.js - Node 中的 Mocking 依赖(主要用于单元测试)

c# - 对对象 'Notes'、数据库 'Sticky'、架构 'dbo' 的 SELECT 权限被拒绝

c# - 如何为 Office 加载项启用身份验证?

python - 设置模拟 asyncio.coroutine 的返回值

c++ - 将线程逻辑与业务逻辑解耦?

c# - ASP.NET MVC 5 + Owin + SimpleInjector

java - 谷歌吉斯。使用 Java EE5 时注入(inject) EJB

c# - 用于实时传输协议(protocol)的开源 .net C# 库