2009-02-05 69 views
24

考虑下列的控制器类:如何从ASP.NET MVC RC1中的ViewResult获取模型数据?

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

我怎样才能在下面的单元测试的模型对象的引用?

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); 
    } 
} 

我已经尝试进入控制器操作,看看正在设置内部字段,但没有运气。

我对ASP.NET MVC的知识是相当有限的,但我的猜测是我没有设置正确的上下文的控制器。

有什么建议吗?

回答

37

尝试:

result.ViewData.Model 

希望这有助于。

+0

fsabau,你是绝对正确的。不能相信我错过了这一点。 D'哦! – 2009-02-05 23:20:28

6

在Asp.Net Mvc框架的Release Candidate版本中,可以通过ViewResult对象的“Model”属性使模型可用。这里是你的测试更准确的版本:

[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); 
} 
相关问题