title: Return View Model in Unit Test
body: <p>I'm using xUnit and .NET Core 2.0. I would like to return the view model to assert against in my unit test.</p>
  
  <p>An example would be:</p>
  
  <pre><code>Project p1 = GetViewModel&lt;Project&gt;(controller.Edit(1));
  </code></pre>
  
  <p>with</p>
  
  <pre><code>private T GetViewModel&lt;T&gt;(IActionResult result) where T : class
  {
      return (result as ViewResult)?.ViewData.Model as T;
  }
  </code></pre>
  
  <p>When I use <code>ViewResult</code> action methods, this works. However, I don't know how to use it for <code>IActionResult</code> action methods, like those used asynchronously when using <code>UserManager</code> objects.</p>
  
  <p>For example:</p>
  
  <pre><code>//This line causes a threading error (Cannot convert from Task&lt;IActionResult&gt; to IActionResult)
  ProjectsListViewModel viewModel = GetViewModel&lt;ProjectsListViewModel&gt;(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;
  </code></pre>
  
  <p>My action method:</p>
  
  <pre><code>[Authorize]
  public async Task&lt;IActionResult&gt; List(int page = 1)
  {
      var user = await userManager.FindByNameAsync(User.Identity.Name);
      if(user != null)
      {
          IQueryable&lt;Project&gt; projectList = GetUserProjects(page, user);
          var model = GetProjectsListViewModel(projectList, page, user);
          return View(model);
      }
      TempData["message"] = "User not found";
      return RedirectToAction("Index", "Home");
  }
  </code></pre>