我正在尝试为我的一个控制器编写一个单元测试来验证视图是否正确返回,但是这个控制器有一个访问HttpContext.Current.Session的基本控制器.每次我创建一个我的控制器的新实例都会调用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);
}
Run Code Online (Sandbox Code Playgroud)
关于如何模拟(使用Moq)在基本控制器中访问的Session的任何想法,以便后代控制器中的测试将运行?