如何在catch块中获取Assert.Multiple的完整断言失败报告?
Great question! When you catch a MultipleAssertException and just call ToString() on it, you only get a condensed summary—but NUnit actually stores all the detailed failure details directly in the exception object. Here's how you can extract the full, report-like error message:
Step 1: Cast the exception to MultipleAssertException
First, since you know the exception thrown from Assert.Multiple is a MultipleAssertException, you can safely cast it to that type to access its special properties (no need for generic Exception unless you're handling other error types too).
Step 2: Access the Results property
This exception has a Results property that holds a list of AssertionResult objects—each one represents a single failed assertion in your multiple block. Every AssertionResult includes the full failure message exactly as it appears in the test report.
Modified Code Example
Here's how to update your test method to capture the full failure details:
[Test] public void AssertMultipleTest() { try { Assert.Multiple(() => { Assert.That(true, Is.False); Assert.That(7, Is.Zero); }); } catch (MultipleAssertException multiEx) { // Build the full error message that matches the test report format var fullErrorMessage = new StringBuilder("One or more failures in Multiple Assert block:"); for (int i = 0; i < multiEx.Results.Count; i++) { fullErrorMessage.AppendLine($"\n{i + 1}) {multiEx.Results[i].Message}"); } // Log the complete message Log.Save(fullErrorMessage.ToString()); // Re-throw the original exception to preserve test failure behavior throw; } }
Bonus: Handle General Exceptions
If you need to catch all exceptions (not just MultipleAssertException), you can add a check for the exception type:
catch (Exception e) { if (e is MultipleAssertException multiEx) { // Build full message as shown above var fullErrorMessage = new StringBuilder("One or more failures in Multiple Assert block:"); for (int i = 0; i < multiEx.Results.Count; i++) { fullErrorMessage.AppendLine($"\n{i + 1}) {multiEx.Results[i].Message}"); } Log.Save(fullErrorMessage.ToString()); } else { // Handle non-multiple assertion exceptions normally Log.Save(e.ToString()); } throw; }
You can also access multiEx.Results[i].StackTrace if you need to capture the stack trace for each individual failed assertion, though the test report usually focuses on the message itself.
内容的提问来源于stack exchange,提问作者Iceeman

