I have the following controller which retrieves data from an endpoint.
It can also sort data depending on whether or not type
is set.
What would be the best approach to testing it?
public class UsersController : ControllerBase
{
[HttpGet]
public async Task<IActionResult> GetAllUsers(string type)
{
using (var client = new HttpClient())
{
try
{
client.BaseAddress = new Uri("http://demo10102020.mockable.io");
var response = await client.GetAsync($"/people");
response.EnsureSuccessStatusCode();
var stringResult = await response.Content.ReadAsStringAsync();
List<User> rawUsers = JsonConvert.DeserializeObject<User[]>(stringResult).ToList();
List<User> sortedUsers = rawUsers;
if(type == "first-name")
{
sortedUsers = rawUsers.OrderBy(o => o.FirstName).ToList();
}
else if(type == "score")
{
sortedUsers = rawUsers.OrderBy(o => o.Score).ToList();
}
return Ok(sortedUsers);
}
catch (HttpRequestException httpRequestException)
{
return BadRequest($"Error getting users: {httpRequestException.Message}");
}
}
}
}
This is my approach so far, I am not sure how to mock the API:
[TestClass]
public class TestPersonController
{
[TestMethod]
public void GetAllPersons_ShouldReturnAllProducts()
{
var testPersons = GetTestPersons();
var controller = new PersonController();
}
private List<Person> GetTestPersons()
{
var testPersons = new List<Person>();
testPersons.Add(new Person { FirstName = "dfdfdf", Surname = "dfdfdf", Score = 100 });
testPersons.Add(new Person { FirstName = "dfsdfsfasf", Surname = "safasfsdaf", Score = 200 });
testPersons.Add(new Person { FirstName = "asffas", Surname = "asdffasdf", Score = 200 });
return testPersons;
}
}