views:

792

answers:

2

Given the following controller class:

public class ProjectController : Controller
{
    public ActionResult List()
    {
        return View(new List<string>());
    }
}

How can I get a reference to the model object in the following unit test?

public class ProjectControllerTests
{
    private readonly ProjectController controller;

    public ProjectControllerTests()
    {
        controller = new ProjectController();
    }

    [Fact]
    public void List_Action_Provides_ProjectCollection()
    {
        var result = (ViewResult)controller.List();

        Assert.NotNull(result);
    }
}

I have tried stepping into the controller action to see what internal fields were being set, but with no luck.

My knowledge of ASP.NET MVC is pretty limited, but my guess is that I am not setting up the controller with a correct context.

Any suggestions?

+3  A: 

In the Release Candidate version of the Asp.Net Mvc framework, the model is made available via the "Model" property of the ViewResult object. Here is a more accurate version of your test:

[Fact]
public void List_Action_Provides_ProjectCollection()
{
    //act
    var result = controller.List();

    //assert
    var viewresult = Assert.IsType<ViewResult>(result);
    Assert.NotNull(result.ViewData.Model);
    Assert.IsType<List<string>>(result.ViewData.Model);
}
Troy
+14  A: 

Try:

result.ViewData.Model

Hope this helps.

Florin Sabau
fsabau, you are absolutely right. Can't believe I missed that. D'oh!
Arnold Zokas