zoukankan      html  css  js  c++  java
  • ASP.NET MVC单元测试Controller时添加上下文的方式

    在ASP.NET MVC中测试Controller时,常常需要在Controller中访问上下文,比方说查询字符串或者form中的内容,而我们测试的时候一般不是在web运行环境下的,所以我们需要做些工作去模拟上下文。

    Controller中代码如下

    public ActionResult Index()
    {
    ViewData[
    "Message"] = Request.QueryString["lfm"];

    return View();
    }

    测试写法如下:

    代码
    [TestMethod]
    public void Index()
    {
    HomeController controller
    = new HomeController();

    var httpContext
    = new Mock<HttpContextBase>();
    var request
    =new Mock<HttpRequestBase>();
    NameValueCollection queryString
    = new NameValueCollection();
    queryString.Add(
    "lfm", "lfm");
    request.Setup(r
    => r.QueryString).Returns(queryString);
    httpContext.Setup(ht
    => ht.Request).Returns(request.Object);

    ControllerContext controllerContext
    = new ControllerContext();
    controllerContext.HttpContext
    = httpContext.Object;
    controller.ControllerContext
    = controllerContext;

    ViewResult result
    = controller.Index() as ViewResult;

    ViewDataDictionary viewData
    = result.ViewData;
    Assert.AreEqual(
    "lfm", viewData["Message"]);
    }

    这里用到了Mock可以参考:

    MoQ(基于.net3.5,c#3.0的mock框架)简单介绍

    如果是form稍作修改即可:

    public ActionResult About()
    {
    ViewData[
    "Message"] = Request.Form["lfm"];
    return View();
    }

    测试代码:

    代码
    [TestMethod]
    public void About()
    {
    // Arrange
    HomeController controller = new HomeController();
    var httpContext
    = new Mock<HttpContextBase>();
    var request
    = new Mock<HttpRequestBase>();
    NameValueCollection queryString
    = new NameValueCollection();
    queryString.Add(
    "lfm", "lfm");
    request.Setup(r
    => r.Form).Returns(queryString);
    httpContext.Setup(ht
    => ht.Request).Returns(request.Object);

    ControllerContext controllerContext
    = new ControllerContext();
    controllerContext.HttpContext
    = httpContext.Object;
    controller.ControllerContext
    = controllerContext;
    // Act
    ViewResult result = controller.About() as ViewResult;

    // Assert
    ViewDataDictionary viewData = result.ViewData;
    Assert.AreEqual(
    "lfm", viewData["Message"]);
    }


    作者:Lance
    出处:http://www.cnblogs.com/nuaalfm/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

  • 相关阅读:
    Learning R笔记(一)
    聚类效果评测-Fmeasure和Accuracy及其Matlab实现
    R—读取数据(导入csv,txt,excel文件)
    R-模式(mode)和类(class)
    SQL Saturday 北京将于7月25日举办线下活动,欢迎参加
    开启微软机器学习之旅(1)--如何从不同数据源将样本数据导入Azure Machine Learning Studio
    微软机器学习Azure Machine Learning入门概览
    JS常用方法
    搭建django环境
    接口测试基础
  • 原文地址:https://www.cnblogs.com/nuaalfm/p/1741088.html
Copyright © 2011-2022 走看看