I use MVC3 and want to test the following action via Microsoft.VisualStudio.TestTools.UnitTesting and Moq:
public ActionResult index()
{
Session.Add("username", "Simon");
var lName = Session["username"] as String;
var lSessionID = Session.SessionID;
return Content(lSessionID);
}
My unit test:
[TestMethod]
public void IndexTest()
{
// Arrange
var contextMock = new Mock<ControllerContext>();
var mockHttpContext = new Mock<HttpContextBase>();
var session = new Mock<HttpSessionStateBase>();
mockHttpContext.Setup(ctx => ctx.Session).Returns(session.Object);
StartController controller = new StartController();
var lResult = controller.index() as ContentResult;
Assert......;
}
My unit-test results in a NullReferenceException:

I have also tried MvcContrib.TestHelper which fails by Session.SessionID with message "not implemented yet".
How can I test my Action with unit tests?
Your mock setup is incomplete.
You need to setup the ControllerContextc.HttpContext to return your mockHttpContext and you also need to use your contextMock in your StartController with setting its ControllerContext property:
So the following setup should work:
var contextMock = new Mock<ControllerContext>();
var mockHttpContext = new Mock<HttpContextBase>();
var session = new Mock<HttpSessionStateBase>();
mockHttpContext.Setup(ctx => ctx.Session).Returns(session.Object);
contextMock.Setup(ctx => ctx.HttpContext).Returns(mockHttpContext.Object);
StartController controller = new StartController();
controller.ControllerContext = contextMock.Object;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With