gpt4 book ai didi

c# - IHeadersDictionary 在模拟后返回 null

转载 作者:行者123 更新时间:2023-12-05 02:14:57 27 4
gpt4 key购买 nike

我正在尝试模拟 IHeadersDictionary,每当我尝试访问它时,我都会返回 Null。

public interface IRequestScopeContext
{
IHeaderDictionary Headers { get; set; }
ISessionInfo SessionInfo { get; set; }
HttpContext HttpContextInfo { get; set; }
}

[SetUp]
public void Setup()
{
var headers = new Dictionary<string, string>
{
{ "Key", "Value"}
} as IHeaderDictionary;

var sessionInfo = new SessionInfo
{
AccountId = "AccountId",
UserId = "UserId",
};

requestScopeContext = new Mock<IRequestScopeContext>();
requestScopeContext.Setup(x => x.Headers).Returns(headers);
requestScopeContext.Setup(x => x.SessionInfo).Returns(sessionInfo);

serviceProvider = new Mock<IServiceProvider>();
serviceProvider.Setup(sp => sp.GetService(It.Is<Type>((Type t) => t.Name.Equals("IRequestScopeContext")))).Returns(requestScopeContext.Object);

httpContextAccessor = new Mock<IHttpContextAccessor>();
httpContextAccessor.Setup(x => x.HttpContext.RequestServices).Returns(serviceProvider.Object);
}

我也试过用

requestScopeContext.Setup(x => x.Headers.Add( "Key", "Value"));

但每当我访问 requestScopeContext.Headers 时,它都会返回 null。

我应该如何模拟这本字典?

我的测试方法是这样的

[Test]
public void SessionHelper_InvokeConstructor_Should_ReturnValidObject()
{
var sessionHelper = new SessionHelper(httpContextAccessor.Object);

Assert.IsNotNull(sessionHelper);
}

这是我正在测试的代码。

public SessionHelper(IHttpContextAccessor httpContextAccessor)
{
IRequestScopeContext requestScopeContext = (IRequestScopeContext)httpContextAccessor.HttpContext.RequestServices.GetService(typeof(IRequestScopeContext));

currentAccountId = requestScopeContext.SessionInfo?.AccountId;
currentUserId = requestScopeContext.SessionInfo?.UserId;
requestId = requestScopeContext.Headers?["key"];
}

最佳答案

正如@Iurii Maksimov 提到的,您的转换不正确 - Dictionary<string, string> 之间没有直接转换和 IHeaderDictionary ,改用这个:

var headers = new HeaderDictionary(new Dictionary<String, StringValues>
{
{ "Key", "Value"}
}) as IHeaderDictionary;

关于c# - IHeadersDictionary 在模拟后返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52855484/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com