ASP.NET MVC unit test controller with HttpContext
Posted
by user299592
on Stack Overflow
See other posts from Stack Overflow
or by user299592
Published on 2010-03-23T04:27:02Z
Indexed on
2010/03/23
4:31 UTC
Read the original article
Hit count: 474
asp.net-mvc
|unit-testing
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);
}
Any ideas on how to mock the Session that is accessed in the base controller so the test in the descendant controller will run?
© Stack Overflow or respective owner