Using IoC for Unit Testing

前端 未结 4 2063
一个人的身影
一个人的身影 2020-11-22 12:13

How can a IoC Container be used for unit testing? Is it useful to manage mocks in a huge solution (50+ projects) using IoC? Any experiences? Any C# libraries that work well

4条回答
  •  野性不改
    2020-11-22 13:01

    Generally speaking, a DI Container should not be necessary for unit testing because unit testing is all about separating responsibilities.

    Consider a class that uses Constructor Injection

    public MyClass(IMyDependency dep) { }
    

    In your entire application, it may be that there's a huge dependency graph hidden behind IMyDependency, but in a unit test, you flatten it all down to a single Test Double.

    You can use dynamic mocks like Moq or RhinoMocks to generate the Test Double, but it is not required.

    var dep = new Mock().Object;
    var sut = new MyClass(dep);
    

    In some cases, an auto-mocking container can be nice to have, but you don't need to use the same DI Container that the production application uses.

提交回复
热议问题