1

我找不到任何导致此单元测试失败的原因,但每次都会失败。

HomeController.cs:

[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = "Whatever";

        return View( model );
    }
}

HomeControllerTest.cs:

[TestClass]
public class HomeControllerTest
{
    [TestMethod]
    public void Index()
    {
        var controller = new HomeController();

        var result = controller.Index() as ViewResult;

        var model = result.ViewData.Model;

        Assert.IsInstanceOfType( model, typeof(string) );
    }
}

结果不为空,result.ViewData 也不为空。但 result.ViewData.Model 始终为空。

到底是什么导致了这个失败?这么简单的测试...

编辑

这更奇怪了。如果我创建一个类,并将该类用作模型,它不会失败。只有当模型是字符串时才会失败!即,这通过了:

HomeController.cs:

[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new SomeClass
            {
                Name = "Whatever"
            };

        return View( model );
    }
}

public class SomeClass
{
    public string Name { get; set; }
}

HomeControllerTest.cs

[TestClass]
public class HomeControllerTest
{
    [TestMethod]
    public void Index()
    {
        var controller = new HomeController();

        var result = controller.Index() as ViewResult;

        var model = result.ViewData.Model;

        Assert.IsInstanceOfType( model, typeof(SomeClass) );
    }
}
4

1 回答 1

2

model就是null为什么。当您将 astring作为参数传递给 时View(string)string实际上是视图名称,而不是 a model

将其转换为 anobject以使用model.

return View((object)model);

View(Object)-ViewResult object通过使用model将 a 呈现viewresponse.

View(String)-ViewResult object使用view呈现 a 的名称创建 a view

于 2013-05-30T21:06:35.067 回答