【问题标题】:Mbunit Factory attribute with ExpectedException带有 ExpectedException 的 Mbunit 工厂属性
【发布时间】:2011-08-01 17:26:59
【问题描述】:

当我使用 Factory 属性时,有没有办法写出我期望某些输入会出现某种异常? 我知道如何使用 Row 属性,但我需要它来动态生成测试输入。

有关返回所提供字符串的逆函数的函数,请参见下面的测试示例:

[TestFixture]
public class MyTestFixture()
{
   private IEnumerable<object[]> TestData
   {
      get
      {
          yield return new object[] { "MyWord", "droWyM" };
          yield return new object[] { null, null }; // Expected argument exception
          yield return new object[] { "", "" };
          yield return new object[] { "123", "321" };
      }
   }

   [Test, Factory("TestData")]
   public void MyTestMethod(string input, string expectedResult)
   {
      // Test logic here...   
   }
}

【问题讨论】:

  • 避免预期异常。如果支持,请使用 Assert.Throws;否则请参阅lostechies.com/jimmybogard/2008/03/11/… 讨论的模式
  • @TrueWill。我不同意这种教条主义的做法。确实 Assert.Throw 更准确,并确保代码的确切预期部分实际上是抛出异常,但是在简单的测试用例中使用 [ExceptionException] 属性仍然更好,尤其是在可读性方面;通常在您测试无效的构造函数或方法参数时。
  • @Yann - James Newkirk 也反对 ExpectedException:jamesnewkirk.typepad.com/posts/2008/06/replacing-expec.html 就我个人而言,我从不在新的测试代码中使用它。

标签: c# unit-testing factory mbunit expected-exception


【解决方案1】:

恐怕没有内置功能可以将元数据(例如预期的异常)附加到来自工厂方法的一行测试参数。

但是,一个简单的解决方案是将预期异常的类型作为测试常规参数传递(null,如果预期不会引发异常)并将测试代码包含在 @987654322 中@ 或 Assert.DoesNotThrow 方法。

[TestFixture]
public class MyTestFixture()
{
  private IEnumerable<object[]> TestData
  {
    get
    {
        yield return new object[] { "MyWord", "droWyM", null };
        yield return new object[] { null, null, typeof(ArgumentNullException) };
        yield return new object[] { "", "", null };
        yield return new object[] { "123", "321", null };
    }
  }

  [Test, Factory("TestData")]
  public void MyTestMethod(string input, string expectedResult, Type expectedException)
  {
    RunWithPossibleExpectedException(expectedException, () => 
    {
       // Test logic here... 
    });
  }

  private void RunWithPossibleExpectedException(Type expectedException, Action action)
  {
    if (expectedException == null)
      Assert.DoesNotThrow(action);
    else
      Assert.Throws(expectedException, action);
  }
}

顺便说一句,有一个额外的Assert.MayThrow 断言来摆脱辅助方法可能会很有趣。它可以只接受 null 作为预期的异常类型。也许你可以创建一个功能请求here,或者你可以提交一个补丁。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-12
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 2011-04-13
    • 2019-03-27
    • 1970-01-01
    相关资源
    最近更新 更多