Kirsten
Kirsten

Reputation: 18198

How do I write a server side unit test that uses a HttpContext?

I am new to writing web applications.

I want to test code that creates a collection

Here is the unit test so far.

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        var accessor = new HttpContextAccessor {HttpContext = new DefaultHttpContext()};
        var helper = new NodeHelper(accessor);
        var nodes = helper.GetNodes();
        Assert.IsTrue(nodes.Count > 0);
        // var nodes = NodeHelper
    }
}

It fails with the error

System.InvalidOperationException: Session has not been configured for this application or request. at Microsoft.AspNetCore.Http.DefaultHttpContext.get_Session()

Upvotes: 2

Views: 444

Answers (1)

Nkosi
Nkosi

Reputation: 247571

Using examples from the DefaultHttpContextTests.cs on Github, it appears you would need to setup some helper classes so that the HttpContext has a usable Session for the test.

private class TestSession : ISession
{
    private Dictionary<string, byte[]> _store
        = new Dictionary<string, byte[]>(StringComparer.OrdinalIgnoreCase);

    public string Id { get; set; }

    public bool IsAvailable { get; } = true;

    public IEnumerable<string> Keys { get { return _store.Keys; } }

    public void Clear()
    {
        _store.Clear();
    }

    public Task CommitAsync(CancellationToken cancellationToken)
    {
        return Task.FromResult(0);
    }

    public Task LoadAsync(CancellationToken cancellationToken)
    {
        return Task.FromResult(0);
    }

    public void Remove(string key)
    {
        _store.Remove(key);
    }

    public void Set(string key, byte[] value)
    {
        _store[key] = value;
    }

    public bool TryGetValue(string key, out byte[] value)
    {
        return _store.TryGetValue(key, out value);
    }
}

private class BlahSessionFeature : ISessionFeature
{
    public ISession Session { get; set; }
}

You could have also mocked the context, session and other dependencies but this way required less setup than having to configure a lot of mocks.

With that the test can be arranged accordingly

[TestClass]
public class NodeHelperTests{
    [TestMethod]
    public void Should_GetNodes_With_Count_GreaterThanZero() {
        //Arrange
        var context = new DefaultHttpContext();
        var session = new TestSession();
        var feature = new BlahSessionFeature();
        feature.Session = session;
        context.Features.Set<ISessionFeature>(feature);
        var accessor = new HttpContextAccessor { HttpContext = context };
        var helper = new NodeHelper(accessor);

        //Act
        var nodes = helper.GetNodes();

        //Assert
        Assert.IsTrue(nodes.Count > 0);            
    }
}

Upvotes: 5

Related Questions