简体   繁体   English

如何模拟MVC方法+构造函数?

[英]How to mock mvc method + constructor?

From this page http://www.dotnetcurry.com/showarticle.aspx?ID=836 , they do this: 他们从此页面http://www.dotnetcurry.com/showarticle.aspx?ID=836进行以下操作:

public class CarDealershipController:Controller
{
  private ICarDealershipController:Controller repository;

  public CarDealershipController:Controller(
    ICarDealershipController:Controller repository)
  {
    this.repository = repository;
  }

  public ActionResult List(string carid)
  {
    var cars = repository.GetCarById(carid);
    return View("List", cars);
  }
}

I've modified the code slightly by adding the carid parameter. 我通过添加carid参数对代码进行了一些修改。 Since this class requires a value sent into its constructor, how does that work if the initial call is: 由于此类需要将值发送到其构造函数中,因此如果初始调用为:

localhost/Home/List/carid

How does the constructor get initialized? 构造函数如何初始化?

Typically you would grab a dependecy resolver like Unity, Ninject or something similar to do this for you. 通常,您会使用像Unity,Ninject之类的依赖解析器或类似的工具来为您执行此操作。 You register a concrete type against any interfaces used and they will construct it and pass it to any constructors that need one. 您针对使用的任何接口注册一个具体类型,它们将构造该类型并将其传递给需要一个的任何构造函数。

To do this, they use a controller factory that hooks into their resolver, rather than the default controller factory, which really only likes empty constructors. 为此,他们使用挂接到解析器的控制器工厂,而不是默认的控制器工厂,后者实际上只喜欢空的构造函数。

此外,我强烈建议James Bender和Jeff McWherter 使用C#进行专业的测试驱动开发

In the case of the constructor I would reccomend using a DI framework to help out with the constructor injection. 对于构造函数,我建议使用DI框架来帮助进行构造函数注入。 In your test you would use a mocking framework to create an instance of the repository. 在测试中,您将使用模拟框架创建存储库的实例。

Seems like you have a typo on the Class name of the repository. 似乎您在存储库的类名称上有错字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM