Mocking response body in IHttpClient/IHttpMethod for unit testing?

Hi folks, Does anyone know how to mock the response body using `IHttpMethod` and `IHttpClient`? Here's what I'm writing so far (simplified): string retrievedNoteJson; /* value not important */ mockHttpClient.Setup(httpClient => httpClient.ExecuteMethod(It.IsAny())) .Callback(httpMethod => httpMethod.ResponseBodyAsStream.Write( retrievedNoteJson.GetByteArrayValue(), 0, retrievedNoteJson.Length )); However, the `ResponseBodyAsStream` property is null for some reason. The property is get-only so I can't replace it. Any ideas?

Best Answer

  • Take a look at DataRoomServiceTest.cs in Website Platform. There are also some notes on mocking in the HttpClient code itself. In SearchServiceTest.cs, this is roughly what is used (I'm sure there are cleaner ways to configure the stream):

    Mock mockHttpClient = new Mock();
    Mock httpWebResponseWrapperMock = new Mock();

    string httpClientResponse = "{\"searchguid\":\"i1234567890123456789012\"}";
    byte[] byteArray = (ASCIIEncoding.Default.GetBytes(httpClientResponse));
    VirtualStream stream = VirtualStream.Create("SetupHttpClientResponseStreamTest");
    stream.Write(byteArray, 0, byteArray.Length);
    stream.Position = 0;
    httpWebResponseWrapperMock.Setup(w => w.GetResponseStream()).Returns(stream);
    mockHttpClient.Setup(c => c.ExecuteMethod(It.IsAny()))
    .Callback((IHttpMethod httpMethod) =>
    httpMethod.HttpResponseWrapper = httpWebResponseWrapperMock.Object);

Answers

  • Thanks! That helped a lot. I used `MemoryStream` to make the stream setup a bit easier, but otherwise that works wonders.