1

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?

Old Fox
  • 8,629
  • 4
  • 34
  • 52
mejobloggs
  • 7,937
  • 6
  • 32
  • 39
  • 2
    It's a BCL method, [you shouldn't test BCL method](http://stackoverflow.com/a/31899094/4332059). Instead I offer you to verify that the method `SetString` was called.(the chart in the link might help you with that...) – Old Fox Dec 12 '15 at 08:34
  • There are several examples on GitHub. https://github.com/aspnet/Testing, the examples are in https://github.com/aspnet/Testing/tree/dev/test/Sample.Tests – JabberwockyDecompiler Dec 14 '15 at 16:53

1 Answers1

3

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();
}
agua from mars
  • 16,428
  • 4
  • 61
  • 70