[英]Unit test ASP.NET MVC 5 Controller with async Task<ActionResult>
Currently I am trying to do some unit test for the Controller and the ViewModel. 目前,我正在尝试对Controller和ViewModel进行一些单元测试。 My Controller function is like this:
我的控制器功能是这样的:
It calls a private method to get user information as a helper function:
它调用一个私有方法来获取用户信息作为辅助函数:
And store the user information in a viewModel then push the viewModel to the client-side. 并将用户信息存储在viewModel中,然后将viewModel推送到客户端。
The Question is how can I do uniting testing for this controller and the associated viewModel? 问题是如何对该控制器和关联的viewModel进行联合测试?
Here is my unit test case: 这是我的单元测试用例:
It returns a Task, which has no viewModel data. 它返回一个没有viewModel数据的Task。 How can I access the data related to the viewModel?
如何访问与viewModel相关的数据?
Let me know if the information I gave is inadequate. 让我知道我提供的信息是否不足。
You should await
the async method and you should follow "async all the way" rule. 您应该
await
异步方法,并且应该遵循“一路异步”规则。
var result = await _controller.Index("644405",DateTime.Now);
And you have to change your unit test method as async
. 而且,您必须将单元测试方法更改为
async
。
Your unit test should look like this: (NUnit example) 您的单元测试应如下所示:(NUnit示例)
[Test]
public async Task ShouldGetValidViewObject_async()
{
var result = await _controller.Index("644405", DateTime.Now);
Assert.// your assertion goes here
}
Or like this (sync) 或像这样(同步)
[Test]
public void ShouldGetValidViewObject()
{
var result = _controller.Index("644405",DateTime.Now).Result;
Assert.// your assertion goes here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.