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

自作多情 提交于 2021-02-07 12:12:13

问题


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.


回答1:


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");



回答2:


Sorry I can't add this as a comment, but if you create your own RequestCookieCollection class, based on the original one in the .net core codebase:

https://github.com/dotnet/aspnetcore/blob/4ef204e13b88c0734e0e94a1cc4c0ef05f40849e/src/Http/Http/src/Internal/RequestCookieCollection.cs

Then you could use this new class to create your cookie collection in your unit tests project. I tried this approach and it works.




回答3:


@Victor6510's answer worked great for me until i needed to create a fake cookie that contained JSON. then i ran into this bug: https://github.com/dotnet/aspnetcore/issues/29304 so i had to come up with additional way.

Using NSubstitute:

[TestClass]
public class ImpersonationMiddlewareTest
{
    private HttpContext _sHttpContext;
    private HttpRequest _sHttpRequest;
    private IRequestCookieCollection _sCookieCollection;

    [TestInitialize]
    public void Initialize()
    {
        _sHttpContext = Substitute.For<HttpContext>();
        _sHttpRequest = Substitute.For<HttpRequest>();
        _sCookieCollection = Substitute.For<IRequestCookieCollection>();
    }

    [TestMethod]
    public async Task Invoke_GoodCookie_CreatesImpersonationIdentity()
    {
        //arrange
        var cookieList = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string,string>("cookiename", "cookievalue")
        };
        _sCookieCollection.GetEnumerator().Returns(e => cookieList.GetEnumerator());
        _sCookieCollection.ContainsKey("cookiename").Returns(true);

        _sHttpRequest.Cookies.Returns(_sCookieCollection);

        _sHttpContext.Request.Returns(_sHttpRequest);

        //act
        myMiddleware.InvokeAsync(_sHttpContext);

        //assert
    }
}


来源:https://stackoverflow.com/questions/60445072/in-net-core-3-1-the-requestcookiecollection-can-no-longer-be-used-to-create-co

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!