0

Let's say I have two ASP.NET Core 7 Web APIs. One gets and uses a value from the other one by sending a request.

1) Sensor API that returns a random int between 0-100:

[ApiController]
[Route("[controller]")]
public class TrafficSensorController : ControllerBase
{
    [HttpGet(Name = "GetTrafficSensor")]
    public int Get()
    {
        return new Random().Next(100);
    }
}

2) Report API that requests to the Sensor API and returns a string representation of the integer value:

[ApiController]
[Route("[controller]")]
public class TrafficReportController : ControllerBase
{
    private static readonly string SENSOR_URL = "https://localhost:7272/TrafficSensor";

    [HttpGet(Name = "GetTrafficReport")]
    public async Task<string> Get()
    {
        var response = await new HttpClient().GetAsync(SENSOR_URL);

        string report = "ERROR!";

        if (response.IsSuccessStatusCode)
        {
            int sensorValue = int.Parse(await response.Content.ReadAsStringAsync());

            if (sensorValue < 30)
                report = "LIGHT TRAFFIC";
            else if (sensorValue < 70)
                report = "MODERATE TRAFFIC";
            else
                report = "HEAVY TRAFFIC";
        }

        return report;
    }
}

Now, I need to write an integration test to simulate an unavailable sensor API that returns 404 or 500 to verify that the report API returning correct error message in such situation. How can I do it?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Burak TARHANLI
  • 190
  • 2
  • 8

1 Answers1

0

First of all, that's probably not how you want to use HttpClient. See Guidelines for using HttpClient or Are You Using HttpClient in The Right Way?

If you had your HttpClient injected, either directly or through an instance of IHttpClientFactory, it could be more or less easily mocked to get the desired response (see answers in Mocking HttpClient in unit tests, or libraries such as mockhttp).

However, if you want to strictly simulate an HTTP response without modifying your code to support HttpClient response mocking (against what is strongly encouraged above), something you could do is use WireMock.Net to mimic the behavior of the local HTTP api itself.

eduherminio
  • 1,514
  • 1
  • 15
  • 31