Skip to content

Commit

Permalink
Check subject for null
Browse files Browse the repository at this point in the history
  • Loading branch information
siewers committed May 16, 2024
1 parent 8c23e34 commit e7b09c3
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
6 changes: 5 additions & 1 deletion Src/FluentAssertions/Primitives/ReferenceTypeAssertions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -432,9 +432,13 @@ public AndConstraint<TAssertions> Satisfy<T>(Action<T> assertion)
Guard.ThrowIfArgumentIsNull(assertion, nameof(assertion), "Cannot verify an object against a <null> inspector.");

Execute.Assertion
.ForCondition(Subject is not null)
.WithDefaultIdentifier(Identifier)
.FailWith("Expected {context:object} to be assignable to {0}{reason}, but found <null>.", typeof(T))
.Then
.ForCondition(Subject is T)
.WithDefaultIdentifier(Identifier)
.FailWith("Expected {context:object} to be assignable to {0}{reason}, but {1} is not.", typeof(T), Subject.GetType());
.FailWith("Expected {context:object} to be assignable to {0}{reason}, but {1} is not.", typeof(T), Subject!.GetType());

string[] failuresFromInspector;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,31 @@ public void Base_class_satisfied_against_sub_class_throws()
$"Expected {nameof(baseClass)} to be assignable to {typeof(SubClass)}, but {typeof(BaseClass)} is not.");
}

[Fact]
public void Nested_assertion_on_null_throws()
{
// Arrange
var complexDto = new PersonAndAddressDto
{
Person = new PersonDto
{
Name = "Buford Howard Tannen",
},
Address = null,
};

// Act
Action act = () => complexDto.Should().Satisfy<PersonAndAddressDto>(dto =>
{
dto.Person.Name.Should().Be("Buford Howard Tannen");
dto.Address.Should().Satisfy<AddressDto>(address => address.City.Should().Be("Hill Valley"));
});

// Assert
act.Should().Throw<XunitException>()
.WithMessage("Expected dto.Address to be assignable to *AddressDto, but found <null>.");
}

private class PersonDto
{
public string Name { get; init; }
Expand Down

0 comments on commit e7b09c3

Please sign in to comment.