使用来自
DefaultHttpContextTests.cs
在Github上,似乎需要设置一些助手类,以便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);
}
}