我在 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/