Moq Mocking and tracking Session values

主宰稳场 提交于 2019-12-01 06:07:21

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

Moq's Setup methods do not work with indexed properties that have string indexes. See here: How to MOQ an Indexed property

It's because you're returning the value in the getter which was passed by value. So everytime you invoke the getter, you get the same value returned.

Change the Returns() to use a delegate so it is evaluated every time. That way you will get the correct value every time :)

Much easier on the eye than a SetupGet embedded inside a SetupSet.

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

I just spent long time trying to figure out the easiest way to do it with moq, below is a copy past of my code that actually worked for me :

var _adminctrl = new Moq.Mock<AdminController>(); //AdminController is my MVC controller

var mock = new Mock<ControllerContext>();
mock.Object.Controller = _adminctrl.Object;
mock.Setup(p => p.HttpContext.Session["UserInfoKey"]).Returns(new ViewModel());
 //here is the catch, attaching the ControllerContext to your controller
_adminctrl.Object.ControllerContext = mock.Object;

hope this helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!