From ec5470e0604fc3f7808284fd0f3fa271b6b1c059 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Valentin=20Breu=C3=9F?= Date: Mon, 13 Oct 2025 18:03:23 +0200 Subject: [PATCH] fix: formatting of nullable types --- .../Formatting/ValueFormatters.Type.cs | 22 +++++++++---------- .../Formatting/ValueFormatters.TypeTests.cs | 16 ++++++++++++++ 2 files changed, 27 insertions(+), 11 deletions(-) diff --git a/Source/aweXpect.Core/Formatting/ValueFormatters.Type.cs b/Source/aweXpect.Core/Formatting/ValueFormatters.Type.cs index 7201ae3ad..c4cd99956 100644 --- a/Source/aweXpect.Core/Formatting/ValueFormatters.Type.cs +++ b/Source/aweXpect.Core/Formatting/ValueFormatters.Type.cs @@ -121,11 +121,7 @@ private static void FormatType( FormatType(value.GetElementType()!, stringBuilder); stringBuilder.Append("[]"); } - else if (TryFindPrimitiveAlias(value, out string? alias)) - { - stringBuilder.Append(alias); - } - else + else if (!AppendedPrimitiveAlias(value, stringBuilder)) { if (value.IsNested && value.DeclaringType is not null) { @@ -163,24 +159,28 @@ private static void FormatType( } #pragma warning restore S3776 - private static bool TryFindPrimitiveAlias(Type value, [NotNullWhen(true)] out string? alias) + private static bool AppendedPrimitiveAlias(Type value, StringBuilder stringBuilder) { if (Aliases.TryGetValue(value, out string? typeAlias)) { - alias = typeAlias; + stringBuilder.Append(typeAlias); return true; } Type? underlyingType = Nullable.GetUnderlyingType(value); - if (underlyingType != null && - Aliases.TryGetValue(underlyingType, out string? underlyingAlias)) + if (underlyingType != null) { - alias = $"{underlyingAlias}?"; + if (Aliases.TryGetValue(underlyingType, out string? underlyingAlias)) + { + stringBuilder.Append(underlyingAlias).Append('?'); + return true; + } + FormatType(underlyingType, stringBuilder); + stringBuilder.Append('?'); return true; } - alias = null; return false; } } diff --git a/Tests/aweXpect.Core.Tests/Formatting/ValueFormatters.TypeTests.cs b/Tests/aweXpect.Core.Tests/Formatting/ValueFormatters.TypeTests.cs index dd8783fda..265a15426 100644 --- a/Tests/aweXpect.Core.Tests/Formatting/ValueFormatters.TypeTests.cs +++ b/Tests/aweXpect.Core.Tests/Formatting/ValueFormatters.TypeTests.cs @@ -208,6 +208,22 @@ public async Task WhenGenericParameter_ShouldUseOnlyName() await That(sb.ToString()).IsEqualTo(expectedResult); } + [Fact] + public async Task WhenNullable_ShouldUseQuestionMarkSyntax() + { + string expectedResult = "DateTime?"; + Type value = typeof(DateTime?); + StringBuilder sb = new(); + + string result = Formatter.Format(value); + string objectResult = Formatter.Format((object?)value); + Formatter.Format(sb, value); + + await That(result).IsEqualTo(expectedResult); + await That(objectResult).IsEqualTo(expectedResult); + await That(sb.ToString()).IsEqualTo(expectedResult); + } + [Fact] public async Task WhenNull_ShouldUseDefaultNullString() {