Skip to content

Commit faa7578

Browse files
authored
Improve ValueDelegateAssertion failure messages if an exception was thrown in the delegate (#2522)
1 parent 159b49b commit faa7578

File tree

2 files changed

+38
-5
lines changed

2 files changed

+38
-5
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
using TUnit.Assertions.AssertConditions.Throws;
2+
3+
namespace TUnit.Assertions.Tests;
4+
5+
public class ThrowInDelegateValueAssertionTests
6+
{
7+
[Test]
8+
public async Task ThrowInDelegateValueAssertion_ReturnsExpectedErrorMessage()
9+
{
10+
var assertion = async () => await Assert.That(() =>
11+
{
12+
throw new Exception("No");
13+
return true;
14+
}).IsEqualTo(true);
15+
16+
await Assert.That(assertion)
17+
.Throws<AssertionException>()
18+
.WithMessageContaining("""
19+
Expected () =>
20+
{
21+
throw new Exception("No");
22+
return true;
23+
} to be equal to True
24+
25+
but An exception was thrown during the assertion: System.Exception: No
26+
""");
27+
}
28+
}

TUnit.Assertions/AssertConditions/ExpectedValueAssertCondition.cs

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ public void WithTransform(Func<TActual?, TActual?> actualTransformation,
1414
{
1515
_transformations.Add((actualTransformation, expectedTransformation));
1616
}
17-
17+
1818
public void WithComparer(Func<TActual?, TExpected?, AssertionDecision> comparer)
1919
{
2020
_customComparers.Add(comparer);
@@ -26,13 +26,13 @@ AssertionMetadata assertionMetadata
2626
)
2727
{
2828
var expected = ExpectedValue;
29-
29+
3030
foreach (var (actualTransformation, expectedTransformation) in _transformations)
3131
{
3232
actualValue = actualTransformation(actualValue);
3333
expected = expectedTransformation(expected);
3434
}
35-
35+
3636
foreach (var result in _customComparers.Select(customComparer => customComparer(actualValue, expected)))
3737
{
3838
switch (result)
@@ -44,8 +44,13 @@ AssertionMetadata assertionMetadata
4444
}
4545
}
4646

47+
if (exception is not null)
48+
{
49+
return FailWithMessage($"An exception was thrown during the assertion: {exception}");
50+
}
51+
4752
return GetResult(actualValue, expected);
4853
}
49-
54+
5055
protected abstract ValueTask<AssertionResult> GetResult(TActual? actualValue, TExpected? expectedValue);
51-
}
56+
}

0 commit comments

Comments
 (0)