[英]How do I correctly instantiate a new controller when using Ninject?
I created a demo Web API application that utilizes Ninject. 我创建了一个使用Ninject的演示Web API应用程序。 The application works fine as I can run it, navigate to the defined route, and get the data I'm expecting. 该应用程序运行良好,可以运行,导航到定义的路线并获取我期望的数据。 Now I want to begin adding unit tests to test the ApiController. 现在,我想开始添加单元测试来测试ApiController。
How do I instantiate a new ApiController? 我如何实例化一个新的ApiController? I'm using var sut = new DogsController();
我正在使用var sut = new DogsController();
but that results in an error, "... does not contain a constructor that take 0 arguments". 但这会导致错误,“ ...不包含带有0个参数的构造函数”。 It's correct I don't have a constructor that takes 0 arguments but Ninject should be taking care of that for me, correct? 没错,我没有带0参数的构造函数,但Ninject应该为我解决这个问题,对吗? How do I resolve this? 我该如何解决?
You will have wired Ninject into the Web API application, not your unit test project. 您将Ninject连接到Web API应用程序中,而不是连接到单元测试项目中。 As a result, Ninject will not be creating the dependencies for your controller, or even your controller as you are explicitly creating it (in the Web API application, the framework creates your controller). 结果,Ninject将不会为您的控制器甚至在您显式创建控制器时创建控制器的依赖关系(在Web API应用程序中,框架会创建您的控制器)。
You could wire Ninject into your unit test project, but that would not be the correct thing to do. 您可以将Ninject连接到单元测试项目中,但这并不是正确的选择。 You should be creating your controller in your tests with a known state, so you should either be passing in known dependencies, or passing in some form of mock dependencies. 您应该在测试中以已知状态创建控制器,因此您应该传递已知依赖关系,或传递某种形式的模拟依赖关系。
A DI container is not some piece of magic that transforms your code every time you write "new Something()". DI容器并不是每次您编写“ new Something()”都会转换代码的魔力。 In your unit test you are newing up the controller by hand (which is good practice btw), but this means you will have to supply the constructor with the proper fake versions of the abstractions the constructor expects. 在单元测试中,您要手动更新控制器(这是一种很好的做法,顺便说一句),但这意味着您将必须向构造函数提供构造函数期望的正确的伪造版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.