我工作的單元測試對我的MVC 4 application.And下面是我想要做單元測試方法之一: -單元測試方法根據型號
[HttpPost]
public ActionResult Index(ProductViewModel model)
{
if (model != null)
{
return PartialView("_ProductGrid", SearchProduct(model));
}
else
{
return RedirectToAction("Index");
}
}
我寫的單元測試方法,但是當我通過代碼覆蓋選項檢查代碼覆蓋時,其他部分顯示爲未被覆蓋。但我不確定原因。
任何人都可以幫我解決這個問題嗎?
下面是我的測試方法的代碼:
[TestMethod]
public void IndexPostTest()
{
// Arrange
const string searchInDescription = "all";
ProductController controller = new ProductController();
ProductViewModel model = new ProductViewModel
{
SearchA = true,
SearchB= true,
SearchIC = true,
Description = searchInDescription
};
TestControllerBuilder builder = new TestControllerBuilder();
builder.InitializeController(controller);
// Act
var result = controller.Index(model) as ActionResult;
var viewmodel = (ProductViewModel)((ViewResultBase)(result)).Model;
int matches = _productService.LookupA("", searchInDescription).Count +
_productService.LookupB("", searchInDescription).Count +
_ProductService.LookupC("", searchInDescription).Count;
if (result != null && viewmodel != null && result.GetType() == typeof(PartialViewResult))
{
// Assert
Assert.IsNotNull(result);
Assert.IsInstanceOfType(viewmodel, typeof(ProductViewModel));
if (viewmodel.Products != null)
Assert.AreEqual(matches, viewmodel.Products.Count());
if (matches > 0 && viewmodel.Products != null && viewmodel.Products.ToList().Count > 0 && viewmodel.Products.ToList()[0].Description != "")
{
Assert.IsTrue(viewmodel.Products.ToList()[0].Description.ToUpper().Contains(searchInDescription.ToUpper()));
}
}
else if (result != null && result.GetType() == typeof(RedirectResult))
{
var redirectResult = result as RedirectResult;
// Assert
Assert.IsNotNull(result);
Assert.AreEqual("Index", redirectResult.Url);
}
}
你能顯示你的單元測試的其他部分? –