【发布时间】:2013-12-19 05:12:21
【问题描述】:
如何对 try-catch 块进行单元测试? 我正在使用 Moq 作为单元测试对象的 ASP.NET MVC 4.0。我想弄清楚如何覆盖 try-catch 块。
下面是我的控制器操作方法的屏幕截图,包括 try-catch 块:
public ActionResult ProductDelete(int id)
{
try
{
ViewBag.Title = "Delete Product";
ProductDetailDto dto = ProductService.GetProductDetail(id);
return View("ProductDelete", BuildProductDetailModel(dto));
}
catch (Exception)
{
throw; // cannot test this line
}
}
您可以看到,当我从测试资源管理器中启用代码覆盖着色选项时,它会显示未覆盖的 catch 块。
下面是我的单元测试方法的屏幕截图:
[TestMethod]
public void ProductDeleteTest()
{
ProductController controller = new ProductController();
var existingProductDetail = _ProductService.GetAllProductsDetails().ToList().FirstOrDefault();
if (existingProductDetail != null)
{
TestControllerBuilder builder = new TestControllerBuilder();
builder.InitializeController(controller);
// Act
var actual = controller.ProductDelete(existingProductDetail.ProductDetailId) as ViewResult;
var viewModel = (ProductDetailModel)actual.Model;
// Assert
Assert.IsNotNull(actual);
Assert.IsInstanceOfType(viewModel, typeof(ProductDetailModel));
Assert.AreEqual(actual.ViewName, "ProductDelete");
}
}
我想弄清楚如何在单元测试方法中覆盖 try-catch 块。
【问题讨论】:
-
请下次粘贴您的代码而不是粘贴图像 - 它可以帮助其他人复制粘贴您的代码,并且当图像从主机中删除时,您的问题不会过时。
-
当然,lazyberezovsky 我会处理的。感谢您的更改。
标签: unit-testing asp.net-mvc-4 mocking try-catch