Get session variable value using Moq..C#

时间:2016-07-11 19:07:12

标签: c# session moq

.Net 4.6.1 C#

I'm using Moq for unit testing. I have session variables that i can set successfully using Moq:

Mock<HttpSessionStateBase> _mockSession = new Mock<HttpSessionStateBase>();
       Mock<HttpContextBase> _mockHttpContext = new Mock<HttpContextBase>();
   _mockHttpContext.SetupGet(ctx => ctx.Session).Returns(_mockSession.Object);
        _mockHttpContext.SetupGet(p => p.Session["windowsUsername"]).Returns("Joe Cool");

If I check the active session, the key "windowsUsername" is there with the value of "Joe Cool". Now I want to get the value of the session key I just created using Moq. This does not work:

 var name = _mockHttpContext.SetupGet(p => p.Session["windowsUsername"]);

How do i get the value of the session object i create using Moq? Thanks

1 个答案:

答案 0 :(得分:3)

Set up _mockSession to return the expected value, not _mockHttpContext.

Mock<HttpSessionStateBase> _mockSession = new Mock<HttpSessionStateBase>();
Mock<HttpContextBase> _mockHttpContext = new Mock<HttpContextBase>();

_mockSession.Setup(x => x["windowsUserName"]).Returns("Joe Cool");

_mockHttpContext.SetupGet(ctx => ctx.Session).Returns(_mockSession.Object);
Assert.AreEqual("Joe Cool", _mockHttpContext.Object.Session["windowsUserName"]);