Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How write a unit test for asynchronous Web API

I have a project in C# and Framework 6. I have a WEB API to call the methods. what is the best way to write a unit test for async WebAPI methods?

This is the method I have:

[HttpGet]
[Route("GetYears")]
public Task<IEnumerable<Year>> GetYearsAsync()
{
     return reditApplicationsRepository.GetYearsAsync();         
}
like image 820
Alma Avatar asked Dec 06 '25 23:12

Alma


1 Answers

You can use await to do this too.

[TestMethod]
public async Task GetYearsTest()
{
    //_sut is the System Under Test,  in this case is an instance of your controller
    var years = await _sut.GetYears();
    //Any Assert that you want
}

And to stub the return of the method creditApplicationsRepository.GetYearsAsync(); use this Task.FromResult(mockReturn).

like image 87
Joel R Michaliszen Avatar answered Dec 09 '25 12:12

Joel R Michaliszen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!