c# - 如何在 asp net core 中模拟 session 对象

标签 c# unit-testing asp.net-core moq asp.net-core-mvc-2.0

我正在使用最小起订量框架编写单元测试。我在基本 Controller setsession() 中调用一个方法,它将使用 SetString("userdata",object) 设置 session ,我还有一个方法 getsession() 这将获得 session 。

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

我在 s.GetStrings.SetString 中收到错误。

由于 GetStringSetString 是扩展方法,可能我需要使用另一种方式来处理它。

你能帮帮我吗?

最佳答案

根据 ISession Extensions source code GetStringSetString 是扩展方法

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

你需要模拟 ISession.SetISession.TryGetValue为了让扩展方法按预期执行。

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

关于c# - 如何在 asp net core 中模拟 session 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47203333/

相关文章:

asp.net - 如何在 asp.net-mvc 单元测试中生成 View ?

unit-testing - Kotlin 中的测试无法访问 protected 方法

asp.net-web-api - 如何使用 IdentityServer4 访问我当前的用户?

c# - Angular Web Api 2 不适用于 POST : 405 Method Not Allowed

c# - 为什么在 linq 中应用 != 时不返回空值

c# - 数据库删除表

c# - AutoFixture 无法创建匿名 MVC Controller

c# - 在 ASP.NET 5 (MVC 6) 中使用 session

c# - 最佳解决方案 : Extension Methods or a New Class?

c# - jQuery 中有一些处理时间段数据类型的方法吗?