asp.net-mvc – ASP.NET MVC单元测试控制器与HttpContext

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – ASP.NET MVC单元测试控制器与HttpContext前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图为我的一个控制器写一个单元测试,以验证视图是否正确返回,但此控制器有一个访问HttpContext.Current.Session的basecontroller。每次我创建一个新的我的控制器的实例是调用basecontroller构造函数和测试失败与一个空指针异常HttpContext.Current.Session。这里是代码
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)在基本控制器中访问的会话,以便后代控制器中的测试将运行?

解决方法

如果你使用 Typemock,你可以这样做:
Isolate.WhenCalled(()=>controller.HttpContext.Current.Session["UserID"])
.WillReturn("your id");

测试代码将如下所示:

[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,expectedViewName);
}
原文链接:https://www.f2er.com/aspnet/254190.html

猜你在找的asp.Net相关文章