coolhand
coolhand

Reputation: 2061

Unit Testing a Task<ViewResult>

Previously, I had a synchronous controller action method that had a unit test with the line

ManageBillsViewModel result = controller.ManageBills(2).ViewData.Model as ManageBillsViewModel;

and all was well. When the action method was changed to an asynchronous Task<ViewResult> method, the above line broke.

I thought I could get it working by adding .Result as in

ManageBillsViewModel result = controller.ManageBills(2).Result.ViewData.Model as ManageBillsViewModel;

but this did not work.

How can I appropriately access the ViewData.Model of an asynchronous method?

Upvotes: 1

Views: 229

Answers (2)

Nkosi
Nkosi

Reputation: 247303

Make the code async all the way down and await the Task<ViewResult> returned from invoking the controller action. The test would also need to made async as well.

[Fact]
public async Task MyTestMethod() {

    //...

    //Act
    var viewResult = await controller.ManageBills(2); 

    ManageBillsViewModel result = viewResult.ViewData.Model as ManageBillsViewModel;

    //Assert

    //...
}

Blocking calls like .Result and .Wait() can lead to deadlocks and should be avoided

Upvotes: 1

zhimin
zhimin

Reputation: 3050

async methods return tasks, you can use

var task = controller.ManageBills(2);
task.Wait();
var result = task.Result;

or

var result = await controller.ManageBills(2);

Upvotes: 0

Related Questions