Search code examples
c#try-catchassert

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. 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.


Solution

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