c# - 如何编写使用 HttpContext 的服务器端单元测试?
问题描述
我是编写 Web 应用程序的新手。
我想测试创建集合的代码
这是到目前为止的单元测试。
[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()
解决方案
使用 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);
}
}
推荐阅读
- javascript - 如何更改 div 类中的数字并更新它?
- python - 如何在 Django 视图中渲染对象?
- c++ - 如何在c ++中取每n个元素的平均值
- python - 如何平均包含一个框架的所有窗口?
- tensorflow - SVHN 数据问题
- python - 如何在 re.search() 中使用两种模式?
- jquery - 如何将 div 分离并添加到没有唯一 ID 的父 div
- jquery - 添加到购物车重复的产品
- sql - 关于 select 1 from dual where exists 你如何解释这个 SQL 代码
- entity-framework - 实体框架和 SQL Server Compact Edition DDEX 提供程序