test case writing in c#

十年热恋 提交于 2019-12-13 08:09:47

问题


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

I write a test method for this..

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

        }

but it's failed.I want to know what's the case.what wrong of this??


回答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.




回答2:


Not entirely clear what's going on here, but it seems that the test is comparing that the exact instance of the SelectList is used in the MVC action and in the unit test.

You should instead compare that each item in the SelectList is the same.



来源:https://stackoverflow.com/questions/19173499/test-case-writing-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!