如何模拟container.Resolve <Type>()

Omu*_*Omu 2 c# moq ioc-container

我有这样的事情

public class HomeController
{
   public ActionResult Index()
   {
      var x = Container.Resolve<IOrganisationService>();
   }
}
Run Code Online (Sandbox Code Playgroud)

当单元测试时,当容器试图解析
任何人都知道如何模拟Container.Resolve()时,我得到一个空引用异常 ?

Mar*_*ann 7

你不能,因为有问题的Resolve方法是一个静态方法.这是静态类型在单元测试(因此代码的一般可组合性)方面被认为是邪恶的众多原因之一.

您似乎正在应用称为服务定位器的(反)模式,并且您当前遇到了与之相关的许多问题之一.

更好的解决方案是使用这样的构造函数注入:

public class HomeController
{
   private readonly IOrganisationService organisationService;

   public HomeController(IOrganisationService organisationService)
   {
       if (organisationService == null)
       {
           throw new ArgumentNullException("organisationService");
       }

       this.organisationService = organisationService;
   }

   public ActionResult Index()
   {
      var x = this.organisationService;
      // return result...
   }
}
Run Code Online (Sandbox Code Playgroud)

您现在可以让您选择的DI容器从外部解析HomeController实例.这是一个更灵活的解决方案.


Ken*_*art 5

问题是,你为什么要以这种方式解决它?如果您反而注入了依赖项,那么您可以轻松地模拟:

public class HomeController
{
    private readonly IOrganisationService organisationService;

    public HomeController(IOrganisationService organisationService)
    {
        this.organisationService = organisationService;
    }

   public ActionResult Index()
   {
      var x = this.organisationService;
   }
}
Run Code Online (Sandbox Code Playgroud)