我想写一个测试,检查我的抽象类构造函数是否正确地处理无效参数。我写了一个测试:
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void MyClassCtorTest()
{
var dummy = Substitute.For<MyClass>("invalid-parameter");
}这个测试没有通过,因为NSubstitute抛出一个TargetInvocationException而不是ArgumentException。我寻找的实际异常实际上是TargetInvocationException的InnerException。我可以编写一个助手方法,如下所示:
internal static class Util {
public static void UnpackException(Action a) {
try {
a();
} catch (TargetInvocationException e) {
throw e.InnerException;
} catch (Exception) {
throw new InvalidOperationException("Invalid exception was thrown!");
}
}
}但我想,应该有某种通用的方法来解决这个问题。有吗?
发布于 2013-10-15 06:33:23
NSubstitute目前还没有解决这个问题的通用方法。
其他一些解决方法包括手动创建抽象类的子类以测试构造函数,或者手动断言内部异常而不是使用ExpectedException。
例如,假设我们有一个需要非负整数的抽象类:
public abstract class MyClass {
protected MyClass(int i) {
if (i < 0) {
throw new ArgumentOutOfRangeException("i", "Must be >= 0");
}
}
// ... other members ...
}我们可以在测试夹具中创建一个子类来测试基类构造函数:
[TestFixture]
public class SampleFixture {
private class TestMyClass : MyClass {
public TestMyClass(int i) : base(i) { }
// ... stub/no-op implementations of any abstract members ...
}
[Test]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void TestInvalidConstructorArgUsingSubclass()
{
new TestMyClass(-5);
}
// Aside: I think `Assert.Throws` is preferred over `ExpectedException` now.
// See http://stackoverflow.com/a/15043731/906
}或者,您仍然可以使用模拟框架并在内部异常上进行断言。我认为这比前一个选项更可取,因为我们不清楚为什么我们要深入研究TargetInvocationException,但无论如何,这里有一个示例:
[Test]
public void TestInvalidConstructorArg()
{
var ex = Assert.Throws<TargetInvocationException>(() => Substitute.For<MyClass>(-5));
Assert.That(ex.InnerException, Is.TypeOf(typeof(ArgumentOutOfRangeException)));
}https://stackoverflow.com/questions/19361261
复制相似问题