问题
[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