如何模拟控制器上下文MOQ上下文、控制器、MOQ

2023-09-03 05:11:31 作者:左眼笑右眼淚

我想出来的最小起订量框架和多达现在我已经打了一个障碍。下面的单元测试失败,因为视图名称属性的实际值是一个空字符串。

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.

任何人都可以点我在正确的方向,请为这是为什么不通过测试?

Could anyone point me in the right direction please as to why this is not passing the test?

[TestMethod]
public void Can_Navigate_To_About_Page()
{
    var request = new Mock<HttpRequestBase>();
    request.Setup(r => r.HttpMethod).Returns("GET");
    var mockHttpContext = new Mock<HttpContextBase>();
    mockHttpContext.Setup(c => c.Request).Returns(request.Object);

    var controllerContext = new ControllerContext(mockHttpContext.Object, 
                                new RouteData(), 
                                new Mock<ControllerBase>().Object);
    var controller = new HomeController();

    controller.ControllerContext = controllerContext;
    var result = controller.About() as ViewResult;

    Assert.AreEqual("About", result.ViewName);
}

下面的方式也产生了一个空的视图名。

The following also yields an empty ViewName.

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

这其中演示了嘲讽,也是不错的TTD我只是困惑,在网络上的例子,我需要做什么等水暖无论是上述第一单元测试的例子工作。

From examples on the web which demonstrate mocking and also good TTD I am just confused as to what other plumbing I need to make either of the above first unit test example work.

干杯,

安德鲁

推荐答案

试验失败的原因是什么决定了视图名,当你没有指定明确的是,在框架的深处。更多precisely在视图引擎,我相信。因此,为了测试这个,因为它代表你就必须模拟出了更多的要求管道。

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);