ankur
ankur

Reputation: 4733

How to Set the content for HttpResponseMessage during a unit test?

I am writing a unit test in which I am testing a service that connects to an external service.

Service code:

var request = new APIRequest
{
    Query = query
};

var response = await _httpService.SendRequestAsync(_configuration.ApiUrl, HttpMethod.Post, request, _configuration.Username, _configuration.Password);

if (response.IsSuccessStatusCode)
{
    var result = await response.Content.ReadAsAsync<Result>();
    return result;
}

The unit test that I have written for the above service method.

public async void GetPerformance_OKResults()
{
    //ARRANGE
    var resultToReturn = MockedEntitiesRepository.mockNetworkResult;
    HttpResponseMessage mockResponse = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
    mockResponse.Content = new ObjectContent(Type.GetType(resultToReturn), resultToReturn, MediaTypeFormatter.)

    mockHttpService.Setup(s => s.SendRequestAsync(applicationConfiguration.Object.Value.ApiUrl, HttpMethod.Post, It.IsAny<object>(), applicationConfiguration.Object.Value.Username, applicationConfiguration.Object.Value.Password)).Returns(Task.FromResult(mockResponse));

    service = new Service(applicationConfiguration.Object, mockHttpService.Object, mockLogger.Object, mockCacheService.Object);

    //ACT
    var result = await Service.GetPerformance(It.IsAny<long>(), It.IsAny<DateTimeOffset>(), It.IsAny<DateTimeOffset>(), It.IsAny<string>());

    // ASSERT
    Assert.Collection(result, item => Assert.Equal(something, something));
}

I want to set the object mockResponse HTTPResponseMessage content with the object resultToReturn in the unit test so that when the code goes makes an actual call it is able to set the value and i can assert on the result.

How can I set the value?

Upvotes: 2

Views: 7243

Answers (1)

mm8
mm8

Reputation: 169218

How can I set the value?

Set the Content property to a StringContent that contains a JSON serialized Result, e.g.:

var result = new Result();
...
mockResponse.Content = new StringContent(JsonConvert.SerializeObject(result));

Upvotes: 12

Related Questions