简体   繁体   中英

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. 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.

The Question is how can I do uniting testing for this controller and the associated viewModel?

Here is my unit test case: 在此处输入图片说明

It returns a Task, which has no viewModel data. How can I access the data related to the 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.

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

And you have to change your unit test method as async .

Your unit test should look like this: (NUnit example)

[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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM