1

当我使用 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...   
   }
}
4

1 回答 1

0

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

但是,一个简单的解决方案是将预期异常的类型作为测试常规参数传递(如果没有预期抛出异常,则为nullAssert.Throws )并将测试代码包含在orAssert.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作为预期的异常类型。也许你可以在这里创建一个功能请求,或者你可以提交一个补丁。

于 2011-08-01T19:35:58.943 回答