如何模拟控制器上下文MOQ [英] How to mock the controller context with moq

查看:171
本文介绍了如何模拟控制器上下文MOQ的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于如何模拟控制器上下文MOQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆