我在一个 Controller 中有一个下面的 Action ,它抛出 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 并重新抛出 InnerException,它被预期为 HttpException:
[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)。
最佳答案
有一个更好的方法来测试这个。我们写了一个名为 AssertHelpers.cs
的类里面有这个方法。这比 ExpectedException
更好的原因是ExpectedException
实际上并不验证它是否被抛出,它只是在抛出时允许测试通过。
例如,如果您将 404 代码更改为返回 200,则您的测试不会失败。
public static void RaisesException<TException>(Action dataFunction, string exceptionIdentifier = null)
{
bool threwException = false;
try
{
dataFunction();
}
catch (Exception e)
{
threwException = true;
Assert.IsInstanceOfType(e, typeof(TException));
if (exceptionIdentifier != null)
Assert.AreEqual(exceptionIdentifier, e.Message);
}
if (!threwException)
Assert.Fail("Expected action to raise exception with message: " + exceptionIdentifier);
}
关于asp.net-mvc-4 - 如何为使用 StatusCode 404 抛出 HttpException 的 Action 编写单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24721266/