简体   繁体   中英

MVC3 Unit Test Controller with Property Injection

I have a MVC3 project that uses property injection . 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. 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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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