I\'m writing a unit test and I call an action method like this
var result = controller.Action(123);
result is ActionResult
and
We placed the following piece in a testsbase.cs allowing for typed models in the tests a la
ActionResult actionResult = ContextGet();
var model = ModelFromActionResult(actionResult);
ModelFromActionResult...
public T ModelFromActionResult(ActionResult actionResult)
{
object model;
if (actionResult.GetType() == typeof(ViewResult))
{
ViewResult viewResult = (ViewResult)actionResult;
model = viewResult.Model;
}
else if (actionResult.GetType() == typeof(PartialViewResult))
{
PartialViewResult partialViewResult = (PartialViewResult)actionResult;
model = partialViewResult.Model;
}
else
{
throw new InvalidOperationException(string.Format("Actionresult of type {0} is not supported by ModelFromResult extractor.", actionResult.GetType()));
}
T typedModel = (T)model;
return typedModel;
}
An example using a Index page and List:
var actionResult = controller.Index();
var model = ModelFromActionResult>((ActionResult)actionResult.Result);