19

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.

1
  • 1
    Thanks for showing how to mock a controller's Session :-) Commented Jan 15, 2014 at 15:06

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.