如何模拟MVC控制器的一部分

时间:2012-11-19 21:29:48

标签: c# asp.net-mvc unit-testing moq

我有一个模拟(使用Moq)设置Mvc3控制器,例如。

[TestMethod]
public void Step_One_Post_Should_Redirect_To_Step_Two()
{
    // this test checks that when I submit a type parameter of StepOneModel and
    // the next button was clicked Request["next"] ,  then goto Step Two
}

阻止此测试运行的唯一方法是从控制器调用Save方法,该方法失败,因为在此测试上下文中未在Session中正确设置值。我真的想从这个单元测试中省略这个数据库调用。

基本上我如何从控制器动作中st /模拟Save(模型)调用?

[HttpPost]
public ActionResult Index(IStepViewModel step)
{
    // after model is deserialized
    if (!string.IsNullOrEmpty(Request["next"]))
    {
        Save(model)  <-- the bit blocking me
    }

    return View(model)  <-- the bit I want to assert against
}

1 个答案:

答案 0 :(得分:1)

我建议使用优秀的库MvcContrib-test helpers

它为您提供开箱即用的模拟会话。

一般概念

  

新MVC.Net框架的一个主要优点是可以轻松测试它。虽然这通常是正确的,但是在许多领域中,测试框架变得困难。 TestHelper通过提供一个控制器工厂来协助创建控制器,其中内部数据成员已正确初始化。其中包括:

     
      
  • HttpContext
  •   
  • 的HttpRequest
  •   
  • 的HttpResponse
  •   
  • HttpSession &lt; -----------------------
  •   
  • 表格
  •   
  • TempData的
  •   
  • 查询字符串
  •   
  • ApplicationPath
  •   
  • PATHINFO
  •   
相关问题