From 42307e821d33eeba2cecc08127f402db0aa66a8c Mon Sep 17 00:00:00 2001 From: Brad Wilson Date: Sun, 24 Jul 2022 17:28:08 -0700 Subject: [PATCH] Fixes #2556: Xunit.Sdk.MultipleException Empty --- src/common/ExceptionUtility.cs | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/src/common/ExceptionUtility.cs b/src/common/ExceptionUtility.cs index df3f03ead..a602127b1 100644 --- a/src/common/ExceptionUtility.cs +++ b/src/common/ExceptionUtility.cs @@ -1,5 +1,8 @@ using System; +using System.Collections.Concurrent; using System.Collections.Generic; +using System.Linq; +using System.Reflection; using Xunit.Abstractions; #if XUNIT_FRAMEWORK @@ -33,6 +36,23 @@ public static string CombineStackTraces(IFailureInformation failureInfo) return GetStackTrace(failureInfo, 0); } +#if XUNIT_FRAMEWORK + static readonly ConcurrentDictionary innerExceptionsPropertyByType = new(); + + static IEnumerable GetInnerExceptions(Exception ex) + { + if (ex is AggregateException aggEx) + return aggEx.InnerExceptions; + + var prop = innerExceptionsPropertyByType.GetOrAdd( + ex.GetType(), + t => t.GetRuntimeProperties().FirstOrDefault(p => p.Name == "InnerExceptions" && p.CanRead) + ); + + return prop?.GetValue(ex) as IEnumerable; + } +#endif + static bool ExcludeStackFrame(string stackFrame) { Guard.ArgumentNotNull("stackFrame", stackFrame); @@ -176,9 +196,9 @@ static void ConvertExceptionToFailureInformation(Exception ex, int parentIndex, indices.Add(parentIndex); #if XUNIT_FRAMEWORK - var aggEx = ex as AggregateException; - if (aggEx != null) - foreach (var innerException in aggEx.InnerExceptions) + var innerExceptions = GetInnerExceptions(ex); + if (innerExceptions != null) + foreach (var innerException in innerExceptions) ConvertExceptionToFailureInformation(innerException, myIndex, exceptionTypes, messages, stackTraces, indices); else #endif @@ -193,6 +213,5 @@ class FailureInformation : IFailureInformation public string[] StackTraces { get; set; } public int[] ExceptionParentIndices { get; set; } } - } }