简体   繁体   中英

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.

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

[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:

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.

How do I configure Session for use inside a unit test?

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
You don't have to test it.

Use Moq to mock ISession :

test 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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