不具有ExpectedException属性的nUnit中的Expect异常 [英] Expect exceptions in nUnit without the ExpectedException attribute
问题描述
我有一个以上参数的方法,只要有任何参数为空,就会抛出ArgumentNullExceptions和ArgumentExceptions来防止输入错误.
因此,有两种显而易见的方法可以对此进行测试:
- 使用[ExpectedException]属性的每个参数进行一次测试
- 使用多个try {} catch块对所有参数进行一次测试
尝试捕获的东西看起来像这样:
try
{
controller.Foo(null, new SecondParameter());
Assert.Fail("ArgumentNullException wasn't thrown");
} catch (ArgumentNullException)
{}
有一个小问题.如果测试通过,则不会调用Assert.Fail,因此将被突出显示为未被覆盖的测试代码(由NCover提供).
我知道这实际上不是问题,因为这是我想要100%覆盖的业务代码,而不是测试代码.还是我很好奇,是否有一种方法可以将多个抛出异常的调用压缩到一个Testcase中而不会丢失LoC?
来自 http://www. andreas-schlapsi.com/2008/03/31/nunit-247-includes-rowtest-extension/
该代码来自Nunit RowTestExtension的源代码,位于 Google代码 > I have methods with more than one parameter that are guarded against bad input by throwing ArgumentNullExceptions and ArgumentExceptions whenever any parameter is null. So there are two obvious ways to test this: The try catch thing would look like that: With one little problem. If the test passes, Assert.Fail never gets called and will therefore be highlighted as not covered test code (by NCover). I know this isn't actually a problem, since it's the business code I want 100% coverage of, not the test code. Still I am curious if there is a way to compress multiple Exception throwing calls into one Testcase without having dead LoCs? From release notes of NUnit 2.4.7
NUnit now includes the RowTest extension, written by Andreas Schlapsi, in it's extension assemblies. This extension allows you to write test methods that take arguments and to provide multiple sets of argument values using the RowAttribute. To use RowTest, your test must reference the nunit.framework.extensions assembly. It adds to NUnit the RowTest feature from MbUnit. You can than write something like: http://www.andreas-schlapsi.com/2008/03/31/nunit-247-includes-rowtest-extension/
The code is from source code for Nunit RowTestExtension at Google code 这篇关于不具有ExpectedException属性的nUnit中的Expect异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
try
{
controller.Foo(null, new SecondParameter());
Assert.Fail("ArgumentNullException wasn't thrown");
} catch (ArgumentNullException)
{}
[RowTest]
[Row(1, 2, 3)]
[Row(3, 4, 8, TestName="Special case")]
[Row(10, 10, 0, TestName="ExceptionTest1"
, ExpectedException=typeof(ArgumentException)
, ExceptionMessage="x and y may not be equal.")]
[Row(1, 1, 0, TestName="ExceptionTest2"
, ExpectedException=typeof(ArgumentException)
, ExceptionMessage="x and y may not be equal.")]
public void AddTest(int x, int y, int expectedSum)
{
int sum = Sum(x, y);
Assert.AreEqual(expectedSum, sum);
}