How to mock the controller context with moq

后端 未结 2 1268
清歌不尽
清歌不尽 2021-01-18 09:14

I am trying out the MOQ framework and up now I have hit a barrier. The following unit test fails because the actual value of the ViewName property is an empty string.

2条回答
  •  天涯浪人
    2021-01-18 09:58

    The reason the test is failing is because what decides the ViewName when you do not specify one explicitly is in the depths of the framework. More precisely in the view engine I believe. So to test this as it stands you would have to mock out a lot more of the request pipeline.

    What I do, and would recommend, is to not rely on the defaults and specify the view explicitly:

    return View("About");
    

    Then the value will be there to test without mocking anything:

    var controller = new HomeController();
    var result = controller.About() as ViewResult;
    Assert.AreEqual("About", result.ViewName);
    

提交回复
热议问题