简体   繁体   English

在单元测试 C# 中使用 Shims/stub 从会话中读取对象

[英]reading object from session using Shims/stub in unit test C#

I have an mvc application .I need to write unit test cases for that application.我有一个 mvc 应用程序。我需要为该应用程序编写单元测试用例。 In controllers of this application im reading an object from session在这个应用程序的控制器中,我从会话中读取一个对象

 objectclass Obj = (objectclass)Session["Object"];

I need to fake this reading of object using Shims/Stubs .我需要使用 Shims/Stubs 来伪造对象的这种读取。

You can create a method to access session data and mock the same like this.您可以创建一个方法来访问会话数据并像这样模拟相同的内容。 Create an interface.创建一个接口。

interface ISessionHelper
{
    object GetSessionValue(string key);        

}

Now you can mock away the method call using any mocking framework.现在您可以使用任何模拟框架来模拟方法调用。

Mock<ISessionHelper> sessionobj = new Mock<ISessionHelper>();
            sessionobj.Setup(a=>a.GetSessionValue(It.IsAny<string>())).Returns(new object());

Replace you seesion access code with将您的访问代码替换为

ISessionHelper obj = new SessionHelper();
obj.GetSessionValue("Object");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM