IHeadersDictionary嘲笑后返回null

时间:2018-10-17 12:59:54

标签: c# asp.net-core nunit moq

我正在尝试模拟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。

我应该如何嘲笑这本词典?

我的TestMethod是这个

[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"];
}

2 个答案:

答案 0 :(得分:0)

如@Iurii Maksimov所述,您的转换是错误的-Dictionary<string, string>IHeaderDictionary之间没有直接转换,请改用此方式:

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

答案 1 :(得分:0)

确定要铸造吗?

var headers = new Dictionary<string, string>
    {
        { "Key", "Value"}
    } as IHeaderDictionary;

在这里,我快速测试了Moq。配置正确。 enter image description here