如何在ASP Net Core中模拟会话对象 [英] How to mock Session Object in asp net core

查看:55
本文介绍了如何在ASP Net Core中模拟会话对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用moq框架编写单元测试.我正在基本控制器setsession()中调用一个方法,它将使用SetString("userdata",object)设置会话,而我又有一个方法getsession()将获得会话.

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

我在s.GetStrings.SetString中遇到错误.

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

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

你能帮我吗?

推荐答案

根据您将需要模拟 ISession.Set

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

这篇关于如何在ASP Net Core中模拟会话对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆