【问题标题】:How to write Unit test for Action that throw HttpException with StatusCode 404如何为使用 StatusCode 404 引发 HttpException 的 Action 编写单元测试
【发布时间】: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。我有两个问题:

  1. 这是编写单元测试的正确方法还是有更多 优雅的测试方式。
  2. 这是否可以在单元测试中检查 该用户正在获取正确的错误页面(在这种情况下为 NotFound)。

【问题讨论】:

    标签: asp.net-mvc-4 unit-testing


    【解决方案1】:

    有一个更好的方法来测试这个。我们编写了一个名为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);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-17
      • 2012-01-06
      相关资源
      最近更新 更多