[英]C# async Task - Unit testing
I am new to C# unit testing and have to test if the method is working properly. 我是C#单元测试的新手,必须测试方法是否正常工作。
Here is what I have so far: 这是我到目前为止:
public async Task<IHttpActionResult> Post(API_FIRM_LINK aPI_FIRM_LINK)
{
db.API_FIRM_LINK.Add(aPI_FIRM_LINK);
await db.SaveChangesAsync();
return Created(aPI_FIRM_LINK);
}
test method: Not really sure if I am on the right path If someone could provide an example based on my test 测试方法:不确定我是否在正确的道路上如果有人可以根据我的测试提供一个例子
public async Task PostTest()
{
////Arrange
API_FIRM_LINKController controller = new API_FIRM_LINKController();
API_FIRM_LINK aPI_FIRM_LINK = null;
IHttpActionResult expectedResult = await controller.Post(aPI_FIRM_LINK);
//act
IHttpActionResult result = await controller.Post(API_FIRM_LINK, aPI_FIRM_LINK);
////Assert
IComparer<IHttpActionResult> comparer = new IHttpActionResultComparer();
// Assert.IsTrue(comparer.Equals(expectedResult, result));
Assert.IsNotNull(result);
Console.Write(result);
Never async void
, basically. 从来没有async void
。
[TestMethod]
public async Task PostTest() {...}
If your testing framework doesn't support Task
tests: change testing framework. 如果您的测试框架不支持Task
测试:更改测试框架。
If you use a modern version of Microsoft.VisualStudio.TestTools.UnitTesting
you can use an async test method, like you do in your question. 如果使用现代版本的Microsoft.VisualStudio.TestTools.UnitTesting
,则可以使用异步测试方法,就像在问题中一样。
If you want to Test whether your Post function returns the expected data, do the following: 如果要测试Post函数是否返回预期数据,请执行以下操作:
[TestMethod()]
public async Task PostTestAsync()
{
var controller = new API_FIRM_LINKController();
// TODO: do some preparations, so you can expect a specific return value
IHttpActionResult expectedResult = ...
// call PostAsync and await for it to finish
Task taskPost = controller.PostAsync(API_FIRM_LINK, aPI_FIRM_LINK);
IHttpActionResult result = await taskPost;
// of course this can be done in one line:
IHttpActionResult result = await controller.PostAsync(API_FIRM_LINK, aPI_FIRM_LINK);
// compare whether result equals expectedResult
// for example: create a class that implements IComparer<IHttpActionResult>
IComparer<IHttpActionResult> comparer = new IHttpActionResultComparer();
Assert.IsTrue(comparer.Equals(expectedResult, result);
}
If you use a test suite where you can't use async tests: 如果您使用的测试套件不能使用异步测试:
[TestMethod()]
public void PostTest()
{
var controller = new API_FIRM_LINKController();
IHttpActionResult expectedResult = ...
// call PostAsync and wait for it to finish
Task taskPost = Task.Run(() => controller.PostAsync(API_FIRM_LINK, aPI_FIRM_LINK));
taskPost.Wait();
IHttpActionResult result = taskPost.Result;
// TODO: compare result with expected result
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.