Mocking Cookies

Request.Cookies

Define a MockRequestCookieCollection class

public class MockRequestCookieCollection : IRequestCookieCollection
{
    private readonly Dictionary<string, string> cookies;

    public MockRequestCookieCollection(Dictionary<string, string> cookies)
    {
        this.cookies = cookies;
    }

    public string this[string key] => cookies.ContainsKey(key) ? cookies[key] : null;
    public int Count => cookies.Count;
    public ICollection<string> Keys => cookies.Keys;
    public bool ContainsKey(string key) => cookies.ContainsKey(key);
    public IEnumerator<KeyValuePair<string, string>> GetEnumerator() => cookies.GetEnumerator();
    public bool TryGetValue(string key, out string value) => cookies.TryGetValue(key, out value);
    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => cookies.GetEnumerator();
}

Using the MockRequestCookieCollection

[Fact]
public async Task OnGetAsync_SetsIssueIdFromCookieWhenFlatplanIdIsZero()
{
    // Arrange
    var mockHttpContext = new DefaultHttpContext();
    var cookies = new MockRequestCookieCollection(new Dictionary<string, string>
    {
        { CookieConstants.ISSUE, "456" }
    });
    mockHttpContext.Request.Cookies = cookies;

    var indexModel = new IndexModel(mockFlatplanService.Object, ...);
    indexModel.HydratePageModel();
    indexModel.PageContext.HttpContext = mockHttpContext;

    // Act
    await indexModel.OnGetAsync();

    // Assert
    Assert.Equal(456, indexModel.IssueId);
}

Response Cookies

Response.Cookies is readonly - it cannot be assigned to so you can't mock it directly and attempt to assign it to the mockHttpContext as in the previous example. What you need to do instead is mock IResponseCookiesFeature then assign it to the Features collection of the mocked HttpContext:

var responseCookiesMock = new Mock<IResponseCookies>();

// Replace the response cookies in the DefaultHttpContext with your mock
var mockResponseCookiesFeature = new Mock<IResponseCookiesFeature>();
mockResponseCookiesFeature.Setup(x => x.Cookies).Returns(responseCookiesMock.Object);
mockHttpContext.Features.Set(mockResponseCookiesFeature.Object);

Then you can verify that the correct cookie was appended to the collection:

responseCookiesMock.Verify(cookies =>
    cookies.Append(CookieConstants.ISSUE, "456",
        It.Is<CookieOptions>(options =>
            options.Expires.HasValue &&
            options.Expires.Value > DateTime.Now.AddDays(29) &&
            options.Expires.Value <= DateTime.Now.AddDays(31))),Times.Once);
Last updated: 8/15/2024 10:14:05 AM

Latest Updates

© 0 - 2025 - Mike Brind.
All rights reserved.
Contact me at Mike dot Brind at Outlook.com