Search code examples
c#unit-testingcookiesasp.net-core-3.1

In .NET Core 3.1, the RequestCookieCollection can no longer be used to create cookies in unit tests


I have just upgraded from .NET Core 2.2 to 3.1. I have tests to confirm that extension methods I've added to HttpContext.Request are working. I was previously able to do things like:

    var context = new DefaultHttpContext();
    var c = new Dictionary<string, string> {{"test", "passed"}};
    context.Request.Cookies = new RequestCookieCollection(cookies);

    var result = context.Request.GetPrimedValue();

Is this impossible now? I tried using Moq for this, but there are far too many things blocking me from being able to set the Cookies property with anything usable, it seems. What is the resolution for this?

note: I understand that this was using an internal class which shouldn't have been internal, so I don't disagree with the internal namespace being hidden, but I'm not sure what my alternatives are.


Solution

  • By manipulating some foundation classes, I am able to produce a mock cookie collection. However it is more like a workaround and might not work in future releases. You might want to give it a try and see how long it can go ...

    With the helper function:

        private static IRequestCookieCollection MockRequestCookieCollection(string key, string value)
        {
                var requestFeature = new HttpRequestFeature();
                var featureCollection = new FeatureCollection();
    
                requestFeature.Headers = new HeaderDictionary();
                requestFeature.Headers.Add(HeaderNames.Cookie, new StringValues(key + "=" + value));
    
                featureCollection.Set<IHttpRequestFeature>(requestFeature);
    
                var cookiesFeature = new RequestCookiesFeature(featureCollection);
    
                return cookiesFeature.Cookies;
        }
    

    Now your unit test code shall become

        var context = new DefaultHttpContext();
    
        context.Request.Cookies = MockRequestCookieCollection("test", "passed");