Skip to content

Commit

Permalink
MaybeCaughtException.cs (#1341)
Browse files Browse the repository at this point in the history
  • Loading branch information
thomhurst authored Dec 2, 2024
1 parent f76a08c commit 8311e9e
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 3 deletions.
32 changes: 31 additions & 1 deletion TUnit.Assertions.Tests/AssertMultipleTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,35 @@ await Assert.That(async () =>
await Assert.That(3).IsEqualTo(6);
}
}).Throws<Exception>().And.HasMessageContaining("Hello World");
}
}

[Test]
public async Task Caught_Exception_In_Scope_Is_Not_Captured()
{
var exception = await Assert.That(async () =>
{
using (Assert.Multiple())
{
await Assert.That(1).IsEqualTo(2);
await Assert.That(2).IsEqualTo(4);

if (1.ToString() == "1")
{
try
{
throw new Exception("Hello World");
}
catch
{
// Ignored
}
}

await Assert.That(3).IsEqualTo(6);
}
}).Throws<Exception>();

await Assert.That(exception!.Message)
.Contains("(This exception may or may not have been caught) System.Exception: Hello World");
}
}
6 changes: 4 additions & 2 deletions TUnit.Assertions/AssertionScope.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ private static void InterceptException(object? sender, FirstChanceExceptionEvent
{
if (GetCurrentAssertionScope() is { } validScope)
{
validScope._exceptions.Add(firstChanceExceptionEventArgs.Exception);
validScope._exceptions.Add(new MaybeCaughtException(firstChanceExceptionEventArgs.Exception));
}
}

Expand All @@ -42,7 +42,9 @@ public void Dispose()
return;
}

if (_exceptions.Count == 1)
// It could be an intercepted exception,
// In which case it should just throw itself, so we don't need to do that
if (_exceptions is [AssertionException])
{
ExceptionDispatchInfo.Throw(_exceptions[0]);
}
Expand Down
4 changes: 4 additions & 0 deletions TUnit.Assertions/Exceptions/MaybeCaughtException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
namespace TUnit.Assertions.Exceptions;

public class MaybeCaughtException(Exception exception)
: Exception($"(This exception may or may not have been caught) {exception.GetType().Namespace}.{exception.GetType().Name}: Hello World", exception);

0 comments on commit 8311e9e

Please sign in to comment.