ASP.NET MVC单元测试控制器的HttpContext [英] ASP.NET MVC unit test controller with HttpContext

查看:129
本文介绍了ASP.NET MVC单元测试控制器的HttpContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个单元测试,我的一个控制器,以验证是否有一种观点正确返回,但该控制器具有一个访问HttpContext.Current.Session一个basecontroller。每次我创造我的控制器的一个新的实例是调用basecontroller构造和测试失败的HttpContext.Current.Session空指针异常。这里是code:

I am trying to write a unit test for my one controller to verify if a view was returned properly, but this controller has a basecontroller that accesses the HttpContext.Current.Session. Everytime I create a new instance of my controller is calls the basecontroller constructor and the test fails with a null pointer exception on the HttpContext.Current.Session. Here is the code:

public class BaseController : Controller
{       
    protected BaseController()
    {
       ViewData["UserID"] = HttpContext.Current.Session["UserID"];   
    }
}

public class IndexController : BaseController
{
    public ActionResult Index()
    {
        return View("Index.aspx");
    }
}

    [TestMethod]
    public void Retrieve_IndexTest()
    {
        // Arrange
        const string expectedViewName = "Index";

        IndexController controller = new IndexController();

        // Act
        var result = controller.Index() as ViewResult;

        // Assert
        Assert.IsNotNull(result, "Should have returned a ViewResult");
        Assert.AreEqual(expectedViewName, result.ViewName, "View name should have been {0}", expectedViewName);
    }

如何(使用MOQ)是在基本控制器访问会话所以在后代控制器测试将跑?嘲笑任何想法

Any ideas on how to mock (using Moq) the Session that is accessed in the base controller so the test in the descendant controller will run?

推荐答案

如果您使用的是 Typemock ,你可以这样做:

If you are using Typemock, you can do this:

Isolate.WhenCalled(()=>controller.HttpContext.Current.Session["UserID"])
.WillReturn("your id");

测试code将看起来像:

The test code will look like:

[TestMethod]
public void Retrieve_IndexTest()
{
    // Arrange
    const string expectedViewName = "Index";

    IndexController controller = new IndexController();
    Isolate.WhenCalled(()=>controller.HttpContext.Current.Session["UserID"])
    .WillReturn("your id");
    // Act
    var result = controller.Index() as ViewResult;

    // Assert
    Assert.IsNotNull(result, "Should have returned a ViewResult");
    Assert.AreEqual(expectedViewName, result.ViewName, "View name should have been {0}", expectedViewName);
}

这篇关于ASP.NET MVC单元测试控制器的HttpContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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