尝试/捕获没有得到C#中的主张引发的内部异常

发布于 2025-01-24 06:30:45 字数 500 浏览 3 评论 0原文

我正在研究一个项目,该项目将在生产中进行给定的单元测试。我想返回单元测试的结果,因此使用try/catch。我假设是否有任何断言失败,它将引发异常。我可以将错误返回为except.message()

try {
   callingUnitTestMethod();
   return new TestResult {Name = "TestName", Status = "Success", Error = "NA"};
} catch(Exception ex) {
   return new TestResult {Name = "TestName", Status = "Fail", Error = ex.Message};
}

现在,这给出了每个方法的同一例外 - “异常是通过调用的目标抛出的。”。但是我想要从TestExplorer运行单元测试时收到的断言消息。我们如何获得适当的例外?

注意:我也尝试了ex.innerexception.tostring()。但是创新的感受是无效的。

I am working on a project which will run the given unit tests in production. I want to return the result of unit test hence using try/catch. I am assuming if any assertion fail it will throw an exception. And I can return the error as exception.message()

try {
   callingUnitTestMethod();
   return new TestResult {Name = "TestName", Status = "Success", Error = "NA"};
} catch(Exception ex) {
   return new TestResult {Name = "TestName", Status = "Fail", Error = ex.Message};
}

Now this is giving the same exception for every method - "Exception has been thrown by the target of an invocation.". But I want the assertion message which we get while running the unit tests from testExplorer. How can we get the proper exception?

Note: I tried ex.InnerException.ToString() as well. But the InnerException is null.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暗喜 2025-01-31 06:30:45

您将需要专门捕获targetInvocationException,然后访问.innerexception作为原因,即

try
{
   callingUnitTestMethod();
   return new TestResult {Name = "TestName", Status = "Success", Error = "NA"};
}
catch (TargetInvocationException tex)
{
   return new TestResult {Name = "TestName", Status = "Fail",
       Error = tex.InnerException.Message};
}
catch (Exception ex)
{
   return new TestResult {Name = "TestName", Status = "Fail", Error = ex.Message};
}

You will need to specifically catch TargetInvocationException, and access the .InnerException as the cause, i.e.

try
{
   callingUnitTestMethod();
   return new TestResult {Name = "TestName", Status = "Success", Error = "NA"};
}
catch (TargetInvocationException tex)
{
   return new TestResult {Name = "TestName", Status = "Fail",
       Error = tex.InnerException.Message};
}
catch (Exception ex)
{
   return new TestResult {Name = "TestName", Status = "Fail", Error = ex.Message};
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文