Moq Mocking and tracking Session values

后端 未结 4 1030
日久生厌
日久生厌 2021-01-13 05:18

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

public class TestHelpers
{
 public long sessionValue = -1;
 pu         


        
相关标签:
4条回答
  • 2021-01-13 06:00

    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);
            });
    
    0 讨论(0)
  • 2021-01-13 06:01

    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);
    
    0 讨论(0)
  • 2021-01-13 06:18

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

    0 讨论(0)
  • 2021-01-13 06:18

    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!

    0 讨论(0)
提交回复
热议问题