Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue Moq'ing HttpResponseMessage

I have the following Method:

public async Task<SecurityRoleDeleteResult> DeleteSecurityRoleByRoleId(int securityRoleId)
{
    string url = $"{_housingDataSecurityConfiguration.HousingDataSecurityWebApiUrl}SecurityRoles/Delete";

    HttpResponseMessage message = _apiClientService.Post(url, securityRoleId);

    if (message.StatusCode == HttpStatusCode.InternalServerError)
    {
        return SecurityRoleDeleteResult.ErrorOccurred;
    }

    int intResult = 0;
    var apiResult = await message.Content.ReadAsStringAsync();
    if (int.TryParse(apiResult, out intResult))
    {
        return (SecurityRoleDeleteResult)intResult;
    }
    else
    {
        return SecurityRoleDeleteResult.ErrorOccurred;
    }
}

I'm now trying to write a unit test for it and so far have:

[Test]
public async Task DeleteSecurityRoleByRoleId()
{
    _mockApiClientService.Setup(a => a.Post(It.IsAny<string>(), It.IsAny<int>()))
        .Returns(new HttpResponseMessage {StatusCode = HttpStatusCode.OK});

    SecurityRoleDeleteResult result = await _securityRoleService.DeleteSecurityRoleByRoleId(It.IsAny<int>());

    Assert.AreEqual(SecurityRoleDeleteResult.Success, result);
}

The issue here is that when running the test in the _securityRoleService.DeleteSecurityRoleByRoleId method at the point I try to set var apiResult message.content is null, because in this instance I'm only mocking so crashes.

How can I mock this out so that my test will work?

like image 665
bilpor Avatar asked May 25 '18 07:05

bilpor


1 Answers

I figured out my issue. Rather than delete my question, I thought I'd post my change to the test. Basically I hadn't mocked the content.

HttpContent content = new StringContent("4");

_mockApiClientService.Setup(a => a.Post(It.IsAny<string>(), It.IsAny<int>()))
    .Returns(new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = content });

So depending on the content type you may want to have returned you may need to change the type of content.

like image 146
bilpor Avatar answered Oct 16 '22 10:10

bilpor