Skip to content

BeWithin().Before for DateTimeOffset? fails with formatting error when value is null #2310

@rokklobster

Description

@rokklobster

Description

Hello.

Recently I observed test failure because of assertion on null date. When checking test logs, error message seemed strange to me:

23:35:53 [ERR] [xUnit.net 00:01:04.67]     FluentAssertions.Specs.Primitives.DateTimeAssertionSpecs+ChainingConstraint.Should_throw_because_of_assertion_failure [FAIL]
23:35:53 [DBG]   Failed FluentAssertions.Specs.Primitives.DateTimeAssertionSpecs+ChainingConstraint.Should_throw_because_of_assertion_failure [9 ms]
23:35:53 [DBG]   Error Message:


23:35:53 [DBG]    Did not expect action "**WARNING** failure message 'Expected {context:the date and time) to be within {0} before {1}, but found a <null> DateTime.' could not be formatted with string.Format


23:35:53 [DBG]    at System.Text.StringBuilder.FormatError()
23:35:53 [DBG]    at System.Text.StringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)
23:35:53 [DBG]    at System.String.FormatHelper(IFormatProvider provider, String format, 
ParamsArray args)
23:35:53 [DBG]    at System.String.Format(IFormatProvider provider, String format, Object[] args)
23:35:53 [DBG]    at FluentAssertions.Execution.MessageBuilder.FormatArgumentPlaceholders(String failureMessage, Object[] failureArgs) in D:\docs\personal\_opensource\fluentassertions\Src\FluentAssertions\Execution\MessageBuilder.cs:line 94"

(I've rewritten test slightly to reproduce the behavior. As you see, thrown exception is not about constraint mismatch.)

Reproduction Steps

// Arrange
DateTimeOffset? nullDateTime = null;

// Act
Action action = () =>
    nullDateTime.Should()
        .BeWithin(TimeSpan.FromSeconds(1))
        .Before(DateTime.Now);

// Assert
action.Should().Throw<Exception>()
    .Which.Message
    .Should().NotContain("{");

Expected behavior

Throw because of date not satisfying constraints.

Actual behavior

Throws because of format string.

Regression?

No response

Known Workarounds

First check the value for null.

Configuration

FluentAssertions nuget 6.11; FA source code at 269ac68
.NET 6, NetCoreApp2.1

Other information

The error looks like the format string is malformed - looks like you can just replace excessive closing paren with closing brace.

Are you willing to help with a pull-request?

Yes, please assign this issue to me.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

Status

✅ Done

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions