How to build an HttpResponseHeaders for the FakeItEasy
Asked Answered
T

4

7

I'm using C# and I need to Test one of my methods that accept System.Net.Http.Headers.HttpRequestHeaders as a parameter. We're using FakeItEasy for the test.

But it seems that the HttpResponseHeaders - does not have the construcotr (and it's sealed), and it uses HttpHeader as base. HttpHeader - has constructor but the Header property only allows get.

Is there a way to build dummy/fake HttpResponseHeaders or HttpResponseMessage and preset the required Header value in it?

Therm answered 20/4, 2020 at 19:7 Comment(0)
L
20

FakeItEasy can't fake a sealed class, nor create a Dummy out of one that doesn't have an accessible constructor, but you could try this:

var message = new HttpResponseMessage();
var headers = message.Headers;
headers.Add("HeaderKey", "HeaderValue");

Just because the Headers are get-only doesn't mean you can't mutate the list.

Luna answered 20/4, 2020 at 20:44 Comment(0)
A
2

Used the solution offered by @Blair for my unit test for a Sendgrid method.

var fakeResponse = new System.Net.Http.HttpResponseMessage();
var fakeResponseHeader = fakeResponse.Headers;
fakeResponseHeader.Add("X-Message-Id", "123xyz");
var response = new SendGrid.Response(System.Net.HttpStatusCode.Accepted, null, fakeResponseHeader);
Antipodes answered 19/3, 2022 at 1:42 Comment(0)
I
1

I used reflection to create a HttpResponseHeaders object:

    static HttpResponseHeaders CreateHttpResponseHeaders()
    {
        var myType = typeof(HttpResponseHeaders);
        var types = Array.Empty<Type>();
        var constructorInfoObject =
            myType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, types, null);

        return (HttpResponseHeaders) constructorInfoObject.Invoke(null);
    }
Irruptive answered 8/1, 2021 at 22:10 Comment(0)
P
0

Using reflection in .Net 6/7/8

    private static HttpResponseHeaders CreateHttpResponseHeaders()
    {
        var constructorInfoObject = typeof(HttpResponseHeaders)
            .GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new [] { typeof(bool) }, null);

        return (HttpResponseHeaders) constructorInfoObject!.Invoke(new object?[] { false });
    }
Pallaton answered 12/5, 2023 at 20:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.