.NET: HttpClient, mocking my IHttpClient interface, but there is an internal object that is NULL and it is sealed

I wonder if anyone can help. I created my own IHttpClient, so I can mock HttpClient using moq. Works very well, but there is an internal object called DetaultRequestHeaders that has the Authorization property.

I install this in my constructor or my class, which accepts in the injected IHttpClient, of course, at runtime everything works as expected. But using Unit Tests, I get an error

Object reference not set to instance.... 

This is because DefaultRequestHeaders is null.

Now, after it is confirmed further, it looks like a type

  HttpRequestHeaders 

but its a sealed class, so I can't even do it

  .Setup(x => x.DefaultRequestHeaders).Returns(return new HttpRequestHeaders()) 

Does anyone have any experience with this?

This is an interface definition.

  HttpRequestHeaders DefaultRequestHeaders { get; } 

Thanks in advance

+4
source share
3 answers

Your syntax Returns not display correctly when calling the Returns method. The fact that HttpRequestHeaders is a sealed class should have nothing to do with whether it can be returned from a call with an in-depth method. Try changing this call to Returns(new HttpRequestHeaders()); or Returns(() => new HttpRequestHeaders()); .

If this does not work (or the specific implementation of HttpRequestHeaders somehow does not suit your needs), you may need to try a framework that can mock private classes, perhaps Moles or JustMock.

-one
source

Just insert the specific HttpClient and mock the HttpMessageHandler ...

http://geekswithblogs.net/abhi/archive/2013/11/20/unit-tests-for-httpclient-using-httpmessagehandler.aspx

+10
source

HttpRequestHeaders only has an internal constructor. But you can do this by creating an HttpRequestMesssage object:

 var message = new HttpRequestMessage(); .Setup(x => x.DefaultRequestHeaders).Returns(message.Headers); 
+1
source

All Articles