[英]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. 我在C#和Framework 6中有一个项目。我有一个WEB API来调用这些方法。 what is the best way to write a unit test for async WebAPI methods?
为异步WebAPI方法编写单元测试的最佳方法是什么?
This is the method I have: 这是我的方法:
[HttpGet]
[Route("GetYears")]
public async Task<IEnumerable<Year>> GetYears()
{
IEnumerable<Year> newYears;
newYears = await creditApplicationsRepository.GetYearsAsync();
return newYears;
}
You can use await
to do this too. 您也可以使用
await
来执行此操作。
[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();
并以stub方式返回方法
creditApplicationsRepository.GetYearsAsync();
use this Task.FromResult(mockReturn)
. 使用此
Task.FromResult(mockReturn)
。
The key objective of a unit test is to test the functionality of the code inside a method. 单元测试的关键目标是测试方法内部代码的功能。 So async or not should not be particularly relevant functionally.
所以async与否在功能上不应该特别相关。
So I would say do something like this: 所以我会说这样做:
[TestMethod]
public void GetYearsTest(){
//This would assume that your web api class has a mockable repository
var yourClass = new YourClass(new MockRepository());
//this is going to run your codes synchronously so you can get an immediate result to test on.
var years = yourClass.GetYears().Result;
//Run whatever test you want to on this
Assert.IsNotNull(years);
}
If the purpose of running an Async test is to determine if your code is thread safe you will have to get creative to determine how to properly test your code to ensure it is in fact safe. 如果运行异步测试的目的是确定您的代码是否是线程安全的,那么您必须具有创造性,以确定如何正确测试代码以确保其实际上是安全的。 In order for me to assist with that I would need to know more about the repo that is being used here or what variables could potentially get thread locked or result in an error.
为了让我能够提供帮助,我需要了解更多关于此处使用的repo或者哪些变量可能会被线程锁定或导致错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.