views:

197

answers:

2

I'm having problems returning a Session value set from mocking using Moq. Using the following

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;
        });
  }
}

When I try to obtain the value outside using

var th = new TestHelpers();
HttpContextBase httpContext = th.FakeHttpContext();

do some stuff that sets Session["id"]

var sessionid = httpContext.Session["id"];

sessionid turns out to be -1. But I can obtain the set session value using

th.sessionValue

What's wrong? Can't I simply return the set value via Moq?

A: 

Moq's Setup methods do not work work with indexed properties that have string indexes. See here: http://stackoverflow.com/questions/340827/how-to-moq-an-indexed-property

Konamiman
if it doesn't work then shouldn't Session["id"] return null and not -1?
seanlinmt
Also, the answers to the question you linked to seem to indicate it works?
Anderson Imes
+2  A: 

I need to stop answering my own questions. It turns out that I needed to mock Session["id"] again like so ...

httpContext.SetupSet(x => x.Session["id"] = It.IsAny<long>())
        .Callback((string name, object val) =>
        {
           sessionValue = (long)val;
           httpContext.SetupGet(x => x.Session["id"]).Returns(sessionValue);
        });
seanlinmt