如何编写使用HttpContext的服务器端单元测试?

时间:2018-10-08 22:51:51

标签: c# unit-testing asp.net-core-2.1

我是写Web应用程序的新手。

我要测试code that creates a collection

这是到目前为止的单元测试。

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

它因错误而失败

  

System.InvalidOperationException:会话尚未配置       用于此应用程序或请求。       在Microsoft.AspNetCore.Http.DefaultHttpContext.get_Session()

1 个答案:

答案 0 :(得分:4)

使用Github上DefaultHttpContextTests.cs的示例,看来您需要设置一些帮助程序类,以便HttpContext具有可用于测试的会话。

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; }
}

您还可以模拟上下文,会话和其他依赖关系,但是这种方式所需的设置少于必须配置大量模拟的时间。

因此可以相应地安排测试

[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);            
    }
}