-1
[HttpGet]
        [Authorize]
        public ActionResult Create() //loads the form
        {
            var categoryList = new SelectList(new[] { "Electronics", "Toys","Books","Sporting Goods"}); //defines the categories
            ViewBag.CategoryList = categoryList;
            return View();
        }

我为此写了一个测试方法..

[TestMethod]

        public void TestCreate() {

            AdvertisementController controller = new AdvertisementController();
            var categoryList = new SelectList(new[] { "Electronics", "Toys", "Books", "Sporting Goods" });
            ViewResult result = controller.Create() as ViewResult;
            Assert.AreEqual(categoryList,result.ViewBag.categoryList);

        }

但它失败了。我想知道这是怎么回事。这有什么问题??

4

2 回答 2

1

Try the following

    [TestMethod]
    public void TestCreate() {

        // Setup
        AdvertisementController controller = new AdvertisementController();
        ViewResult result = controller.Create() as ViewResult;

        var expectedCategories = new SelectList(new[] { "Electronics", "Toys", "Books", "Sporting Goods" }).ToList();

        // Execute
        var actualCategories = result.ViewBag.categoryList.ToList();

        // Assert
        Assert.IsNotNull(result); 
        Assert.AreEqual(expectedCategories[0], actualCategories[0]);
        Assert.AreEqual(expectedCategories[1], actualCategories[2]);
        Assert.AreEqual(expectedCategories[2], actualCategories[3]);
        Assert.AreEqual(expectedCategories[3], actualCategories[4]);
        Assert.AreEqual(expectedCategories[4], actualCategories[5]);

    }

Basically in this, you're verifying that result is equal to something, and that EACH item within the array matches the expected item.

note: I didn't wire this up in an IDE so it might have some mistakes.

于 2013-10-04T05:10:18.417 回答
0

不完全清楚这里发生了什么,但似乎测试正在比较SelectListMVC 操作和单元测试中使用的确切实例。

相反,您应该比较 SelectList 中的每个项目是否相同。

于 2013-10-04T04:59:03.173 回答