3

我是.net 中单元测试/mvc 的新手。我一直在关注 Pro ASP.net MVC 4, 4th edition 这本书。在书中,他们创建了一家假商店。在其中一个示例中,他们使用 viewbag 将数据传递给局部视图。他们有一个有效的关联单元测试,但是我重写了示例以通过视图模型而不是 viewbag 容器传递数据,现在我似乎无法找到一种方法来重写单元测试以通过。有人介意帮我吗?我只是想弄清楚一个小时,这是一种失败的努力。以下是工作测试。

// Arrange
// - create the mock repository
Mock<IProductRepository> mock = new Mock<IProductRepository>();
mock.Setup(m => m.Products).Returns(new Product[] {
    new Product {ProductID = 1, Name = "P1", Category = "Apples"},
    new Product {ProductID = 4, Name = "P2", Category = "Oranges"},
}.AsQueryable());

// Arrange - create the controller
NavController target = new NavController(mock.Object);

// Arrange - define the category to selected
string categoryToSelect = "Apples";

// Action
string result = target.Menu(categoryToSelect).ViewBag.SelectedCategory;

// Assert
Assert.AreEqual(categoryToSelect,result);

所以现在我已经通过视图模型(成功地)传递了数据......

public class CategoryInfoViewModel:IEnumerable<string>
{
    public IEnumerable<string> Categories { get; set; }
    public string SelectedCategory { get; set; }

    public IEnumerator<string> GetEnumerator()
    {
        return Categories.GetEnumerator();
    } 

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    } 
}

如何更改测试以使其正常工作?非常感谢各位!

4

2 回答 2

0

好的,我终于想通了。我是个白痴。我制作的视图模型类称为 CategoryInfoViewModel。所以我不得不这样做...

 // Action
 CategoryInfoViewModel result = (CategoryInfoViewModel)target.Menu(categoryToSelect).Model;

 // Assert
 Assert.AreEqual(categoryToSelect, result.SelectedCategory);
于 2013-11-05T19:49:51.647 回答
0

假设操作的返回类型是 ViewResult,您可以使用以下代码:

// Arrange
// - create the mock repository
Mock<IProductRepository> mock = new Mock<IProductRepository>();
mock.Setup(m => m.Products).Returns(new Product[] {
    new Product {ProductID = 1, Name = "P1", Category = "Apples"},
    new Product {ProductID = 4, Name = "P2", Category = "Oranges"},
}.AsQueryable());

// Arrange - create the controller
NavController target = new NavController(mock.Object);

// Arrange - define the category to selected
string categoryToSelect = "Apples";

// Action
string result = (ViewResult)target.Menu(categoryToSelect);

// Assert
Assert.AreEqual(categoryToSelect,result.Model);

我希望这对你有用。问候,

于 2013-11-05T18:58:05.607 回答