Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test fails because of Sessions

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:

enter image description here

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?

like image 614
Simon Avatar asked Jan 19 '26 10:01

Simon


1 Answers

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;
like image 69
nemesv Avatar answered Jan 21 '26 07:01

nemesv