简体   繁体   English

如何对ASP.NET 5 / MVC 6 Session进行单元测试?

[英]How to unit test ASP.NET 5 / MVC 6 Session?

I have a function in a class library that updates a session variable. 我在类库中有一个函数来更新会话变量。 ISession is passed in as a parameter from the controller so the function can change the session var. ISession作为参数从控制器传入,因此该函数可以更改会话var。

I'm wanting to test this function to ensure the session variable is updated correctly. 我想测试此函数以确保会话变量正确更新。

First however, I'm just trying to get started with a basic unit test with XUnit, but I can't get Session to work 首先,我只是尝试使用XUnit开始基本的单元测试,但是我无法使Session工作

[Fact]
public void CreateSessionVariable()
{
    var httpContext = new DefaultHttpContext();
    httpContext.Session.SetString("MyVar", "Hi");
    Assert.True(httpContext.Session.Get("MyVar") != null);
}

On httpContext.Session.SetString I get the error: httpContext.Session.SetString我收到错误:

Session has not been configured for this application or request 尚未为此应用程序或请求配置会话

I know in an MVC6 app you have to do things like services.AddSession() and app.UseSession() but I don't know how to set those for a unit test. 我知道在MVC6应用程序中你必须做像services.AddSession()app.UseSession()这样的事情,但我不知道如何为单元测试设置它们。

How do I configure Session for use inside a unit test? 如何配置Session以在单元测试中使用?

Microsoft.AspNet.Session is already tested, you can read tests codes here https://github.com/aspnet/Session/blob/dev/test/Microsoft.AspNet.Session.Tests/SessionTests.cs Microsoft.AspNet.Session已经过测试,你可以在这里阅读测试代码https://github.com/aspnet/Session/blob/dev/test/Microsoft.AspNet.Session.Tests/SessionTests.cs
You don't have to test it. 你不必测试它。

Use Moq to mock ISession : 使用Moq模拟ISession

test project.json 测试project.json

{
  "version": "1.0.0-*",
  "dependencies": {
      "{YourProject under test}": "",
      "xunit": "2.1.0",
      "xunit.runner.dnx": "2.1.0-rc1-*"
    },
  "commands": {
      "test": "xunit.runner.dnx"
  },
  "frameworks": {
    "dnx451": {
      "dependencies": {
        "Moq": "4.2.1312.1622" 
      }
    }
  }
}

A test can look like this: 测试可能如下所示:

[Fact]
public void CreateSessionVariableTest()
{
    var sessionMock = new Mock<ISession>();
    sessionMock.Setup(s => s.Get("MyVar")).Returns("Hi);

    var classToTest = new ClassToTest(sessionMock.Object);
    classToTest.CreateSessionVariable();
}

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

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