coolhand
coolhand

Reputation: 2061

Return View Model in Unit Test

I'm using xUnit and .NET Core 2.0. I would like to return the view model to assert against in my unit test.

An example would be:

Project p1 = GetViewModel<Project>(controller.Edit(1));

with

private T GetViewModel<T>(IActionResult result) where T : class
{
    return (result as ViewResult)?.ViewData.Model as T;
}

When I use ViewResult action methods, this works. However, I don't know how to use it for IActionResult action methods, like those used asynchronously when using UserManager objects.

For example:

//This line causes a threading error (Cannot convert from Task<IActionResult> to IActionResult)
ProjectsListViewModel viewModel = GetViewModel<ProjectsListViewModel>(controller.List(2));
//unlike ViewModel, IActionResult does not have a ViewData property so this throws an error
ProjectsListViewModel result = controller.List(2).ViewData.Model as ProjectsListViewModel;

My action method:

[Authorize]
public async Task<IActionResult> List(int page = 1)
{
    var user = await userManager.FindByNameAsync(User.Identity.Name);
    if(user != null)
    {
        IQueryable<Project> projectList = GetUserProjects(page, user);
        var model = GetProjectsListViewModel(projectList, page, user);
        return View(model);
    }
    TempData["message"] = "User not found";
    return RedirectToAction("Index", "Home");
}

Upvotes: 1

Views: 1961

Answers (1)

Nkosi
Nkosi

Reputation: 247323

Tasks would need to be awaited to get access to the action result.

ProjectsListViewModel result = GetViewModel<ProjectsListViewModel>(await controller.List(2));

The test method would also need to be async-await

public async Task Should_Return_ProjectsListViewModel() {
    //Arrange

    //...

    //Act
    IActionResult actual = await controller.List(2);

    //Assert
    ViewResult viewResult = actual as ViewResult;
    viewResult.Should().NotBeNull(); //FluentAssertions

    ProjectsListViewModel result = viewResult.ViewData.Model as ProjectsListViewModel;
    result.Should().NotBeNull();
}

Upvotes: 1

Related Questions