【发布时间】:2014-09-03 11:14:24
【问题描述】:
我在控制器中有以下操作,它抛出 HttpException 状态码 404:
public async Task<ActionResult> Edit(int id)
{
Project proj = await _service.GetProjectById(id);
if( proj == null)
{
throw new HttpException(404, "Project not found.");
}
}
为了测试这种情况,我编写了下面的测试用例,其中我正在捕获 AggregationException 并重新抛出预期为 HttpException 的 InnerException:
[TestMethod]
[ExpectedException(typeof(HttpException),"Project not found.")]
public void Edit_Project_Load_InCorrect_Value()
{
Task<ActionResult> task = _projectController.Edit(3);
try
{
ViewResult result = task.Result as ViewResult;
Assert.AreEqual("NotFound", result.ViewName, "Incorrect Page title");
}
catch (AggregateException ex)
{
throw ex.InnerException;
}
}
此测试成功运行并返回 ExpectedException。我有两个问题:
- 这是编写单元测试的正确方法还是有更多 优雅的测试方式。
- 这是否可以在单元测试中检查 该用户正在获取正确的错误页面(在这种情况下为 NotFound)。
【问题讨论】:
标签: asp.net-mvc-4 unit-testing