A .NET Unit Test without a parameterless constructor, to facilitate dependency injection

前端 未结 2 1341
逝去的感伤
逝去的感伤 2021-02-19 22:00

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

I\'m currently using AutoFac 2.2.4,

2条回答
  •  盖世英雄少女心
    2021-02-19 22:03

    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.

    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.

    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.

提交回复
热议问题