views:

84

answers:

2

I'm writing a unit test and I call an action method like this

var result = controller.Action(123);

result is ActionResult and I need to get the model somehow, anybody knows how to do this ?

A: 

In my version of ASP.NET MVC there is no Action method on Controller. However, if you meant the View method, here's how you can unit test that the result contains the correct model.

First of all, if you only return ViewResult from a particular Action, declare the method as returning ViewResult instead of ActionResult.

As an example, consider this Index action

public ViewResult Index()
{
    return this.View(this.userViewModelService.GetUsers());
}

you can get to the model as easily as this

var result = sut.Index().ViewData.Model;

If your method signature's return type is ActionResult instead of ViewResult, you will need to cast it to ViewResult first.

Mark Seemann
It's better to cast to ViewResultBase (this covers partials); also (rarely) one may consider using reflection to check ViewData/Model properties and get Model (in case there're unknown view result types).
queen3
Good point on ViewResultBase, but why would you ever use Reflection for something like this?
Mark Seemann
A: 

consider a = ActionResult;

ViewResult p = (ViewResult)a;
p.ViewData.Model
Omu