使用异步任务<actionresult>对ASP.NET MVC 5控制器进行单元测试

时间:2018-01-24 07:12:05

标签: c# asp.net-mvc unit-testing

目前我正在尝试为Controller和ViewModel进行一些单元测试。我的控制器功能是这样的: enter image description here 它调用私有方法将用户信息作为辅助函数: enter image description here

将用户信息存储在viewModel中,然后将viewModel推送到客户端。

问题是如何对此控制器和相关的viewModel进行联合测试?

这是我的单元测试用例: enter image description here

它返回一个没有viewModel数据的Task。如何访问与viewModel相关的数据?

如果我提供的信息不充分,请告诉我。

2 个答案:

答案 0 :(得分:3)

你应该await async方法,你应该遵循“async all a way”规则。

var result = await _controller.Index("644405",DateTime.Now);

您必须将单元测试方法更改为async

答案 1 :(得分:0)

您的单元测试应如下所示: (NUnit示例)

[Test]
public async Task ShouldGetValidViewObject_async()
{
    var result = await _controller.Index("644405", DateTime.Now);
    Assert.// your assertion goes here
}

或者像这样(同步)

[Test]
public void ShouldGetValidViewObject()
{
    var result = _controller.Index("644405",DateTime.Now).Result;
    Assert.// your assertion goes here
}
相关问题