【问题标题】:Using NUnit to test HTTP status of a WebFaultException使用 NUnit 测试 WebFaultException 的 HTTP 状态
【发布时间】:2014-03-22 17:33:31
【问题描述】:

我想编写一个单元测试来确保我得到一个带有从特定方法抛出的 404 状态码的 WebException。

WebException 位很简单:

[Test]
[ExpectedException(typeof(WebFaultException))]
public void CheckForWebFaultException()
{
  var myClass = new MyClass();
  myClass.MyMethod();
}

但是,这可能是 404、400、401 或无数其他 http 代码中的任何其他代码。

我可以做一个 try/catch/Assert.True 但这感觉就像一个 hack。有没有办法针对抛出的异常的属性进行断言?

类似

Assert.Throws(typeof(WebFaultException), myClass.MyMethod(), wfx => wfx.StatusCode == HttpStatusCode.NotFound);

【问题讨论】:

    标签: unit-testing exception-handling nunit


    【解决方案1】:

    我在正确的路线上,Assert.Throws 实际上返回了抛出的异常。

    [Test]
    public void CheckForWebFaultException()
    {
      var myClass = new MyClass();  
      var ex = Assert.Throws<WebFaultException>(() => myClass.MyMethod());
      Assert.AreEqual(HttpStatusCode.NotFound, ex.StatusCode);    
    }
    

    请注意,我已经取出了 [ExpectedException(typeof(WebFaultException))],因为现在处理了异常,如果保留它,测试将失败。

    Assert.Throws 确保异常是由myClass.MyMethod() 抛出的,第二个断言检查状态码。

    【讨论】:

      猜你喜欢
      • 2023-01-17
      • 1970-01-01
      • 2020-08-02
      • 2011-02-10
      • 1970-01-01
      • 2019-07-19
      • 1970-01-01
      • 2017-04-29
      • 1970-01-01
      相关资源
      最近更新 更多