简体   繁体   English

具有属性注入的MVC3单元测试控制器

[英]MVC3 Unit Test Controller with Property Injection

I have a MVC3 project that uses property injection . 我有一个使用属性注入的MVC3项目。 Within my controllers I make a call to a service class. 在我的控制器中,我调用了一个服务类。 As I mentioned it uses property injection (with unity ) instead of resolving this through the constructor. 正如我提到的,它使用属性注入(带有unity )而不是通过构造函数来解决。 I have searched all over trying to find an example of a unit test that resolves these dependencies within my controller but everything seems to refer to constructer DI. 我四处搜寻,试图找到一个可以解决控制器内这些依赖关系的单元测试示例,但似乎所有内容都涉及构造器DI。 I'm getting frustrated. 我感到沮丧。 Any help would be great. 任何帮助都会很棒。

Example of Controller: 控制器示例:

  [Dependency]
  public ITrainingService trainingService { get; set; } 

  public ActionResult Index(MyTrainingView myTrainingView)
  {
    //Load all training items into view object
    myTrainingView.training = trainingService.getTraining(myTrainingView.trainingId);
    myTrainingView.videos = trainingService.getTrainingVideos(myTrainingView.trainingId);
    myTrainingView.visuals = trainingService.getTrainingVisuals(myTrainingView.trainingId);
    myTrainingView.exams = trainingService.getTrainingExams(myTrainingView.trainingId);

    return View(myTrainingView);
  }

I'm trying to resolve the trainingService when running my unit test. 我正在尝试运行单元测试时解决trainingService。 I have found countless examples for mocking and resolving dependencies using constructor dependency but nothing when it comes to property injection. 我发现了无数使用构造函数依赖项来模拟和解析依赖项的示例,但在属性注入方面却一无所获。

You don't need to rely on unity in your unit tests. 您不需要在单元测试中依靠统一性。

Something like this would do the trick: 这样的事情可以解决问题:

    [Test]
    public void GetTrainingById()
    {
        var mockService = MockRepository.GenerateMock<ITrainingService>();
        mockService.Stub(service => service.getTraining(123)).Return(new ImaginaryClass());

        var sut = new TrainingController();
        sut.trainingService = mockService;

        var myTrainingView = new MyTrainingView();
        sut.Index(myTrainingView);

        Assert.AreEqual(expected, myTrainingView.training);
    }

If you must use unity in your unit tests, you could just instantiate the UnityContainer in your test and use the RegisterInstance to register the objects you want to inject. 如果必须在单元测试中使用unity,则UnityContainer在测试中实例化UnityContainer并使用RegisterInstance注册要注入的对象。

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

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