[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);
}
但它失败了。我想知道是什么情况。这有什么不对吗?
答案 0 :(得分:1)
尝试以下
[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]);
}
基本上,在此,您将验证结果是否等于某个内容,并且数组中的每个项目与预期项目匹配。
注意:我没有在IDE中连接它,因此它可能有一些错误。
答案 1 :(得分:0)
并不完全清楚这里发生了什么,但似乎测试正在比较MVC操作和单元测试中使用的SelectList
的确切实例。
您应该比较SelectList中的每个项是否相同。