c# - 为什么我不能从构造函数中捕获这个异常?
问题描述
ArgumentNullException
在此测试代码中,尽管已处理,为什么测试失败并显示?
[Test]
public void ExceptionBehaviorTest()
{
// This works. An instance is returned
var testInstance = (TestClass)Activator.CreateInstance(typeof(TestClass), "Hello World");
Assert.NotNull(testInstance);
// This passes. Exception is generated and caught
Assert.Throws<ArgumentNullException>(() => new TestClass(null));
try
{
// This throws ArgumentNullException but the catch handler is not invoked. This fails the test
testInstance = (TestClass)Activator.CreateInstance(typeof(TestClass), (string)null);
Assert.Fail("Should not get here");
}
catch (ArgumentNullException)
{
}
}
private sealed class TestClass
{
public TestClass(string arg)
{
Argument = arg ?? throw new ArgumentNullException(nameof(arg));
}
public string Argument
{
get;
}
}
如果我在调试器中运行代码,它会在TestClass
ctor 中停止,表示未处理异常。但是调用函数在堆栈中是可见的,因此问题与在不同线程上执行的某些部分无关。
[背景:在我的实际代码中,我正在迭代一堆类并测试它们是否有一个带有特定参数的 ctor。这是为了防止以后出现运行时错误,因为类是使用依赖注入构造的。]
解决方案
这是在文档中
目标调用异常
被调用的构造函数抛出异常。
所以你需要抓住TargetInvocationException
这种情况,如果你喜欢你也可以使用when
,虽然我不确定它对你的测试有多大帮助
catch (TargetInvocationException ex) when (ex.InnerException is ArgumentNullException)
{
Console.WriteLine("Caught");
}
推荐阅读
- guptateamdeveloper - 打印 QRP 而不警告打印机边距?
- javascript - 在对象中传递键并在 *ngFor 中使用它
- javascript - 使用 vega-lite 时禁用工具提示标签被截断/增加工具提示字符限制
- python - Python:解析终端响应
- c - 执行“./a.out”时如何重定向“中止(核心转储)”等信息
- java - 我有多个布局文件,但应用程序只识别 1 个?
- android - 如何使用 Intl 在 Flutter 中获取当前的语言环境文本方向
- javascript - JavaScript 正则表达式(?!)不适用于包含文字 \n\r 的文本?
- php - SQL Server - Windows 身份验证
- batch-file - 并行运行 bat 文件并等待它们完成后再运行新的 bat 文件集