单元测试中的依赖注入,我如何注入我注入的class?

Dependency injection in unit tests, how do I inject into my injected class?

我有一个 Web API 项目,我在其中绑定到所有 classes。

//NinjectWebCommon.cs
private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<DAL.IDAL>().To<DAL.MyDAL>();
    kernel.Bind<BUS.IService>().To<BUS.MyService>();
    kernel.Bind<DAL.IUser>().To<API.User>().InSingletonScope();
}    

这很好用。

我尝试使用以下方法为我的 DAL 设置单元测试。

//Test1.cs
public DAL.IDAL db { private get; set; }

[TestInitialize]
public void InitializeTests()
{
    var kernel = new Ninject.StandardKernel();
    db = kernel.Get<DAL.MyDAL>();
    kernel.Bind<DAL.IUser>().To<Test.User>().InSingletonScope();;
}

我收到错误

Error activating IUser
No matching bindings are available and the type is not self-bindable.
Activation Path:
  2) Injection of dependency IUser into property user of type MyDAL
  1) Request for MyDAL

我在 MyDAL 中有 IUser class。我不确定这里到底发生了什么。

//MyDAL.cs
public class MyDAL
{
    [Inject]
    public IUser user { get; set; }

    //other functions
    //...
}

"Flip" 这两行。

db = kernel.Get<DAL.MyDAL>();
kernel.Bind<DAL.IUser>().To<Test.User>().InSingletonScope();

又名:

kernel.Bind<DAL.IUser>().To<Test.User>().InSingletonScope();
db = kernel.Get<DAL.MyDAL>();

调用前你必须"define"。

好的,我明白了。多亏了这个Cheat Sheet

基本上我需要专门将我的价值注入我的class。

public DAL.IDAL db { private get; set; }

[TestInitialize]
public void InitializeTests()
{
    var kernel = new Ninject.StandardKernel();
    db = kernel.Get<DAL.MyDAL>(new PropertyValue("user", new Test.User());
}