【发布时间】: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