'How to unit test this C# method which returns List of teams from an api?
I want to unit test this C# method which returns List of teams from an api?Any Help?
public List<FootballTeam> LoadTeamStats(string seasonId)
{
HttpResponseMessage response = _footballApiClient.GetAsync($"{FootballApiUrls.GET_TEAMS_FOR_SEASON}/{seasonId}?api_token={ApiKeyValue}&include=stats:filter(season_id|{seasonId})").Result;
if (response.IsSuccessStatusCode)
{
string teamData = response.Content.ReadAsStringAsync().Result;
var dto = JsonConvert.DeserializeObject<FootballTeamBySeasonQuery>(teamData);
return ParseTeamDetailsFromApi(dto.Teams);
}
else
{
throw new ApiException(response.ReasonPhrase);
}
}
Solution 1:[1]
One thing you could test here is LoadTeamStats method returns some expected data when response.IsSuccessStatusCode is true and otherwise LoadTeamStats method throws the ApiException.
To test it you could mock _footballApiClient. But as we see _footballApiClient is HttpClient that can't be mocked easily, hence you need to hide it behind your own interface then mock it.
So write your own interface for HttpClient and mock it with one of mocking libs like Moq and then write the unit test.
Solution 2:[2]
First of all would suggest to separate concerns of this method. Leave all the HTTP / REST related functionality in your WebAPi controller actions but extract the logic itself into their own class. I normally call them business-service and I put them into my non-web-related assembly of the project (normally called xyz.Core.dll).
Check out the Single responsibility principle of SOLID if this isn't familiar to you. Lesson I've learned: this makes unit-testing your logic (eg. query and parsing) way easier as you don't need to mock/fake HttpRequest etc. There are libraries that can mock this stuff too but it can get tricky quickly.
Then you can use any unit-testing framework for C# for writing tests for the logic like the new TeamDataReader and the TeamDetailsParser classes. Frameworks like Nunit, XUnit or MSTest will do a good job here. I can also recommend the Fake-Library FakeItEasy and the FluentAssertions library.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | AlbertK |
| Solution 2 | Glorfindel |
