How to mock Session Object in asp net core

元气小坏坏 提交于 2019-11-28 09:18:50

问题


I am writing unit tests using moq framework. I am calling one method in base controller setsession() which will set session using SetString("userdata",object) and I have one more method getsession() which will get session.

var sessionMock = new Mock<ISession>();
sessionMock.Setup(s => s.GetString("userdata")).Returns(Object);--failing
sessionMock.Setup(s => s.SetString("userdata",object));--failing

I am getting the error in s.GetString and s.SetString.

As GetString and SetString are extension methods may be I need to use another way to handle it.

Can you please help me?


回答1:


According to ISession Extensions source code GetString and SetString are extension methods

public static void SetString(this ISession session, string key, string value)
{
    session.Set(key, Encoding.UTF8.GetBytes(value));
}

public static string GetString(this ISession session, string key)
{
    var data = session.Get(key);
    if (data == null)
    {
        return null;
    }
    return Encoding.UTF8.GetString(data);
}

public static byte[] Get(this ISession session, string key)
{
    byte[] value = null;
    session.TryGetValue(key, out value);
    return value;
}

You will need to mock ISession.Set and ISession.TryGetValue in order to let the extension methods execute as expected.

//Arrange
var sessionMock = new Mock<ISession>();
var key = "userdata";
var value = new byte[0];

sessionMock.Setup(_ => _.Set(key, It.IsAny<byte[]>()))
    .Callback<string, byte[]>((k,v) => value = v);

sessionMock.Setup(_ => _.TryGetValue(key, out value))
    .Returns(true);



回答2:


here's my soultion to question

) create a new mock ISession & new mock HttpContext

//Arrange
var mockContext = new Mock<HttpContext>();
var mockSession = new Mock<ISession>();

) create session value

SomeClass sessionUser = new SomeClass() { Property1 = "MyValue" };
var sessionValue = JsonConvert.SerializeObject(sessionUser);
byte[] dummy = System.Text.Encoding.UTF8.GetBytes(sessionValue);

) setup mocks to return serialized obj

mockSession.Setup(x => x.TryGetValue(It.IsAny<string>(), out dummy)).Returns(true); //the out dummy does the trick
mockContext.Setup(s => s.Session).Returns(mockSession.Object);

) inject to mvc httpcontext (in my case a Page instead of a typical controller)

_classUnderTest.PageContext = new Microsoft.AspNetCore.Mvc.RazorPages.PageContext();
_classUnderTest.PageContext.HttpContext = mockContext.Object;

Now all is up and running, when i hit the session getvalue i receive that serializes object

Greez Nic



来源:https://stackoverflow.com/questions/47203333/how-to-mock-session-object-in-asp-net-core

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