Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Unit Testing - Sessions

Having searched StackOverflow, and Google I think what I'm doing is suppose to be right, however results don't seem to be going well

    [TestMethod]
    public void LoginAction_Should_Return_View_and_User_Authenticated()
    {
        // Arrange
        var mock = new Mock<ControllerContext>();
        var mockSession = new Mock<HttpSessionStateBase>();
        mock.Setup(p => p.HttpContext.Session).Returns(mockSession.Object);

        var testData = FakeUserData.CreateTestUsers();
        var repository = new FakeUserRepository(testData);
        var controller = new AccountController(repository);
        controller.ControllerContext = mock.Object;

        // Act
        var result = controller.Login("testuser1", "testuser1");

        // Assert
        Assert.AreEqual("testuser1", controller.HttpContext.Session["Username"]);
        Assert.IsTrue((bool)controller.HttpContext.Session["IsAuthenticated"]);
        Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult));
    }

When I run the test the value of controller.HttpContext.Session["Username"] is null, however I set the value to the username using a Session helper. Am I doing something completely wrong, or something else? Any help would be greatly appreciated.

like image 634
Tom Bell Avatar asked Sep 06 '09 10:09

Tom Bell


1 Answers

Use Mock.Verify to check if underlying code tried to set Session["Username"].

If your code needs to set session variable and use it - take a look here.

Quickstart is priceless too.

like image 74
Arnis Lapsa Avatar answered Oct 02 '22 12:10

Arnis Lapsa