不带无参数构造函数的.NET单元测试,以促进依赖项注入 [英] A .NET Unit Test without a parameterless constructor, to facilitate dependency injection

查看:82
本文介绍了不带无参数构造函数的.NET单元测试,以促进依赖项注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让单元测试不依赖于调用 container.Resolve< T>()作为依赖项.

I'm trying to have the unit tests not rely on calling container.Resolve<T>() for their dependencies.

我当前正在使用 AutoFac 2.2.4,并尝试过 xUnit.NET NUnit ,但都存在此问题:

I'm currently using AutoFac 2.2.4, and tried xUnit.NET and NUnit, but both have this issue:

没有为此对象定义无参数构造函数

No parameterless constructor defined for this object

如何解决这个问题?是支持该功能的特定单元测试框架,还是只是配置上述框架的方式?

How do I get past this issue? Is it a particular unit testing framework that will support this, or just how said framework is configured?

我不应该这样做吗?还是可以将测试类设置为与仅具有依赖项的构造函数一起使用?

Should I not be doing this? Or can I set up the test class to work with the constructor that has it's only dependency?

以下是一些代码:

public class ProductTests : BaseTest
{
    readonly private IProductRepository _repo;

    public ProductTests(IProductRepository r)
    {
        _repo = r;
    }

    //working unit tests here with default constructor
} 

我选择在基类构造函数中错误地初始化容器吗?

Did I choose to initialise the container wrongly in the base class constructor?

public abstract class BaseTest
{
    protected BaseTest()
    {
        var builder = new ContainerBuilder();
        builder.RegisterType<ProductRepository>().As<IProductRepository>();
        builder.Build();
    }
}

推荐答案

最初的问题确实归因于测试框架的设计方式.它们都需要无参数的构造函数才能实例化测试实例.当然是这样.使用这些框架,就不必依赖构造函数进行测试初始化​​.这就是SetUp方法的目的.总而言之,测试类本身不适合注入.

The initial problem is indeed due to how the testing frameworks are designed. They all require a parameterless constructor in order to instantiate test instances. And rightfully so. With these frameworks, the constructor is not to be relied on for test initialization. That is the purpose of the SetUp method. All in all, the test classes themselves are not suited for injection.

并且IMO,当您开发不依赖于容器的测试时,这将成为非问题.毕竟,每个测试类都应该关注一个被测系统"(SUT).为什么设置方法不直接实例化该系统并提供每个依赖项(通常以伪造形式)?通过这种方式,您已经有效地从测试中删除了另一个不必要的依赖,即IoC框架.

And IMO, this becomes a non-issue when you develop your tests to not depend on the container. After all, each test class should focus on one "system under test" (SUT). Why not have the setup method instantiate that system directly and provide each dependency (usually in the form of fakes)? By doing it this way you have effectively removed another unnecessary dependency from your tests, namely the IoC framework.

另一方面,在测试中涉及IoC框架的唯一时间是在容器测试"中.这些测试的重点是在使用应用程序或程序集模块初始化容器后,验证是否可以从容器中解析某些服务.

On a side note: the only time I involve the IoC framework in my tests is in my "container tests". These tests focus on verifying that certain services can be resolved from the container after the container have been initialized with application or assembly modules.

这篇关于不带无参数构造函数的.NET单元测试,以促进依赖项注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆