gpt4 book ai didi

c# - NSubstitute 中的 TargetInvocationException

转载 作者:行者123 更新时间:2023-11-28 20:31:46 24 4
gpt4 key购买 nike

我想编写一个测试来检查我的抽象类构造函数是否正确处理了无效参数。我写了一个测试:

[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void MyClassCtorTest()
{
var dummy = Substitute.For<MyClass>("invalid-parameter");
}

这个测试没有通过,因为 NSubstitute 抛出一个 TargetInvocationException 而不是 ArgumentException。我寻找的实际异常实际上是 TargetInvocationExceptionInnerException。我可以编写一个辅助方法,例如:

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!");
}
}
}

但我想,应该有某种通用的方法来解决这个问题。有吗?

最佳答案

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)));
}

关于c# - NSubstitute 中的 TargetInvocationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19361261/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com