IdependencyResolver 在使用最小起订量的单元测试中始终为 null

IdependencyResolver is always null in unit test using moq

我已经在一个 mvc 项目中实现了 ninject,它按预期工作,现在我想进行单元测试,但似乎无法让它工作:

控制器:

 private IDependencyResolver _resolver;

 public HomeController(IDependencyResolver resolver)
 {
        _resolver = resolver;
 }

  public ActionResult Index()
  {
        var model = _resolver.GetService<ISignUpViewModel>();
        return PartialView("Login", model);
  }

单元测试

    private IDependencyResolver _resolverMock;

    [TestMethod]
    public void SignUpTest()
    {

        var ctrl = new HomeController(_resolverMock);
        var signUpMock = new Mock<ISignUpViewModel>();

        ctrl.Index();
        ctrl.ViewData.Model = signUpMock;

        //Assert.AreEqual("", "");

    }

解析器始终为空。

我看过 Ninject.MockingKernel.Moq 我应该在那里设置解析器吗?

知道我哪里出错了吗?

谢谢

在单元测试中你手动创建了HomeController实例,所以你需要mock IDependencyResolver。例如:

var resolverMock = new Mock<IDependencyResolver>();
var ctrl = new HomeController(resolverMock.Object);
....