rep*_*rat 3 design-patterns dependency-injection ninject c#-4.0
我是使用ninject和Dependency Injection的新手,并且在使用它时遇到了问题.
我尝试在我的类库中使用Ninject,并构建集成测试.现在,我在很多例子中看到,使用ninject只是指定了DI模块,如下所示:
Public Class DIModule : NinjectModule
public override void Load()
{
Bind<IUSAServices>().To<USAServices>();
}
Run Code Online (Sandbox Code Playgroud)
然后在我的测试类中,我尝试调用我的依赖是这样的:
[TestClass]
public class USAIntegrationTests
{
private readonly IUSAServices _usaService;
public USAIntegrationTests(IUSAServices usaServices)
{
_usaService = usaServices;
}
[TestMethod]
public void ValidateUserTests()
{
Assert.IsTrue(_usaService.ValidateUser("username1", "password1"));
}
}
Run Code Online (Sandbox Code Playgroud)
并得到此错误:
Unable to get default constructor for class USATests.IntegrationTests.USAIntegrationTests.
Run Code Online (Sandbox Code Playgroud)
但是,我阅读文档并尝试这样:
[TestClass]
public class USAIntegrationTests
{
private readonly IUSAServices _usaService;
public USAIntegrationTests()
{
using (IKernel kernel = new StandardKernel(new DIModule()))
{
_usaService = kernel.Get<IUSAServices>();
}
}
[TestMethod]
public void ValidateUserTests()
{
Assert.IsTrue(_usaService.ValidateUser("mantab", "banget"));
}
}
Run Code Online (Sandbox Code Playgroud)
测试工作正常.我的问题是,为什么我会收到这个错误?是有办法解决它吗?提前致谢.
单元测试框架要求您的测试类具有默认构造函数.您通常无法将DI容器与它们集成.您不必使用构造函数注入,而是必须直接从代码中调用容器,尽管对于单元测试,您通常根本不应该有容器(但是对于集成测试,这是可以的).