From c84789140a21dd2f4c83ffa054d5c7cd13b212b4 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Mon, 22 Dec 2025 13:22:56 +0000 Subject: [PATCH] feat: enhance assertion exception messages to include inline 'because' reasons --- .../AssertConditions/BecauseTests.cs | 22 +++++++++++++++++++ TUnit.Assertions/Core/Assertion.cs | 18 ++++++++------- 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/TUnit.Assertions.Tests/AssertConditions/BecauseTests.cs b/TUnit.Assertions.Tests/AssertConditions/BecauseTests.cs index 0c4c88137f..a75232e91c 100644 --- a/TUnit.Assertions.Tests/AssertConditions/BecauseTests.cs +++ b/TUnit.Assertions.Tests/AssertConditions/BecauseTests.cs @@ -144,4 +144,26 @@ await Assert.That(variable).IsFalse().Because(because1) var exception = await Assert.ThrowsAsync(action); await Assert.That(exception.Message).Contains(because1).And.Contains(because2); } + + [Test] + public async Task Because_Message_Appears_Inline_With_Expectation() + { + var expectedMessage = """ + Expected to be false, because this is the reason + but found True + + at Assert.That(variable).IsFalse().Because("this is the reason") + """; + + var variable = true; + + var action = async () => + { + await Assert.That(variable).IsFalse().Because("this is the reason"); + }; + + var exception = await Assert.ThrowsAsync(action); + await Assert.That(exception.Message.NormalizeLineEndings()) + .IsEqualTo(expectedMessage.NormalizeLineEndings()); + } } diff --git a/TUnit.Assertions/Core/Assertion.cs b/TUnit.Assertions/Core/Assertion.cs index cda35ff933..1b9e06afc7 100644 --- a/TUnit.Assertions/Core/Assertion.cs +++ b/TUnit.Assertions/Core/Assertion.cs @@ -212,22 +212,24 @@ public OrContinuation Or /// protected Exception CreateException(AssertionResult result) { - var message = $""" - Expected {GetExpectation()} - but {result.Message} - - at {Context.ExpressionBuilder} - """; + var expectation = GetExpectation(); if (_becauseMessage != null) { - // Check if message already starts with "because" to avoid duplication + // Append because message inline with the expectation var becausePrefix = _becauseMessage.StartsWith("because ", StringComparison.OrdinalIgnoreCase) ? _becauseMessage : $"because {_becauseMessage}"; - message += $"\n\n{becausePrefix}"; + expectation = $"{expectation}, {becausePrefix}"; } + var message = $""" + Expected {expectation} + but {result.Message} + + at {Context.ExpressionBuilder} + """; + return new AssertionException(message); }