In a unit testing scenario, you can (and should) provide your own implementation (or mock/stub/fake) of IMyInterface as so:public class MyTestClass : IMyInterface{ public IEnumerable<MyObject> Get() { List<MyObject> list = new List<MyObject>(); // populate list return list; } }并在您的测试中:[TestClass]public class MyControllerTests{ MyController _systemUnderTest; IMyInterface _myInterface; [TestInitialize] public void Setup() { _myInterface = new MyTestClass(); _systemUnderTest = new MyController(_myInterface); }}因此对于单元测试MyController的范围,IMyInterface的实际实现无关紧要(并且 不应该 重要),只有接口本身才重要.我们已经通过MyTestClass提供了IMyInterface的伪"实现,但是您也可以通过Moq或RhinoMocks这样的模拟来实现.So for the scope of unit testing MyController, the actual implementation of IMyInterface does not matter (and should not matter), only the interface itself matters. We have provided a "fake" implementation of IMyInterface through MyTestClass, but you could also do this with a mock like through Moq or RhinoMocks.最重要的是,您实际上不需要依赖项注入容器来完成测试,只需一个单独的,可控的,实现/模拟/存根/伪造的测试类依赖项即可.Bottom line, you do not actually need the dependency injection container to accomplish your tests, only a separate, controllable, implementation/mock/stub/fake of your tested classes dependencies. 这篇关于如何使用构造函数依赖项注入对ASP.NET核心应用程序进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-24 13:35