Search code examples
c#asp.net-corenunitmoq

IHeadersDictionary returning null after mocking


I am trying to mock IHeadersDictionary and whenever I try to access it I returns 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);
}

I also tried using

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

but whenever I access requestScopeContext.Headers it returns me null.

How should I mock this dictionary ?

My TestMethod is this

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

    Assert.IsNotNull(sessionHelper);
}

And this is the piece of code I am testing.

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

Solution

  • As @Iurii Maksimov mentioned, your casting is incorrect - there is no direct cast between Dictionary<string, string> and IHeaderDictionary, use this instead:

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