简体   繁体   English

Try/catch 没有得到 c# 中 Assert 抛出的内部异常

[英]Try/catch is not getting the inner exception thrown by Assert in c#

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.我想返回单元测试的结果,因此使用 try/catch。 I am assuming if any assertion fail it will throw an exception.我假设如果任何断言失败,它将抛出异常。 And I can return the error as exception.message()我可以将错误作为 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.但是我想要从 testExplorer 运行单元测试时得到的断言消息。 How can we get the proper exception?我们怎样才能得到适当的异常?

Note: I tried ex.InnerException.ToString() as well.注意:我也尝试了 ex.InnerException.ToString() 。 But the InnerException is null.但是 InnerException 是 null。

You will need to specifically catch TargetInvocationException , and access the .InnerException as the cause, ie您将需要专门捕获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};
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM