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?