我在使用Moq从模拟返回Session值集时遇到问题.使用以下内容
public class TestHelpers
{
public long sessionValue = -1;
public HttpContextBase FakeHttpContext()
{
var httpContext = new Mock<HttpContextBase>();
var session = new Mock<HttpSessionStateBase>();
httpContext.Setup(x => x.Session).Returns(session.Object);
httpContext.SetupGet(x => x.Session["id"]).Returns(sessionValue);
httpContext.SetupSet(x => x.Session["id"] = It.IsAny<long>())
.Callback((string name, object val) =>
{
sessionValue = (long)val;
});
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试获取外部使用的值
var th = new TestHelpers();
HttpContextBase httpContext = th.FakeHttpContext();
Run Code Online (Sandbox Code Playgroud)
做一些设置Session ["id"]的东西
var sessionid = httpContext.Session["id"];
Run Code Online (Sandbox Code Playgroud)
sessionid结果为-1.但我可以使用获取设置的会话值
th.sessionValue
Run Code Online (Sandbox Code Playgroud)
怎么了?我不能简单地通过Moq返回设定值吗?