In my application I use a custom PaginatedList<T>
class that extends List
with some extra properties. Given that FluentAssertion only compares the content of the list and excludes extra properties when using BeEquivalentTo()
, I wrote my own EquivalencyStep
to check the extra property manually. However, I can’t get it to print the name of the properties properly.
Here is a minimal (not) working example:
Models:
public interface IPaginatedList {
int CurrentPage { get; }
int PageSize { get; }
int ItemsCount { get; }
}
public sealed class PaginatedList<T> : List<T>, IPaginatedList {
public PaginatedList(IEnumerable<T> items, int currentPage, int pageSize, int itemsCount) {
this.CurrentPage = currentPage;
this.PageSize = pageSize;
this.ItemsCount = itemsCount;
this.AddRange(items);
}
public int CurrentPage { get; }
public int PageSize { get; }
public int ItemsCount { get; }
}
public sealed class Result<T> {
public bool IsSuccess { get; set; }
public T? ValueOrDefault { get; set; }
}
EquivalencyStep:
public sealed class PaginatedListEquivalencyStep : EquivalencyStep<IPaginatedList> {
protected override EquivalencyResult OnHandle(Comparands comparands, IEquivalencyValidationContext context, IEquivalencyValidator nestedValidator) {
if (comparands.Subject is not IPaginatedList subject) {
throw new NotSupportedException();
}
if (comparands.Expectation is not IPaginatedList expectation) {
throw new NotSupportedException();
}
// Assert custom properties
using (new AssertionScope($"{context.CurrentNode.Description}.{nameof(subject.ItemsCount)}")) {
subject.ItemsCount.Should().Be(expectation.ItemsCount);
}
// [...]
// Assert that the content of the collection is the same
new EnumerableEquivalencyStep().Handle(comparands,
context,
nestedValidator);
return EquivalencyResult.AssertionCompleted;
}
}
Program:
Result<PaginatedList<int>> result = new() {
IsSuccess = true,
ValueOrDefault = new PaginatedList<int>(
[1, 2, 3],
1,
3,
3
)
};
Result<PaginatedList<int>> expected = new() {
IsSuccess = true,
ValueOrDefault = new PaginatedList<int>(
[1, 2, 3],
1,
3,
10 // This value is diferent: should fail.
)
};
result.Should()
.BeEquivalentTo(
expected,
opt => opt
.Using(new PaginatedListEquivalencyStep()));
Expected error message:
Expected property result.ValueOrDefault.ItemsCount to be 10, but found 3 (difference of -7)
What it actually prints:
Expected property using (new AssertionScope($"{context.CurrentNode.Description}.{nameof(subject.ItemsCount)}")) {subject.ItemsCount.ValueOrDefault.ItemsCount to be 10, but found 3 (difference of -7).
What is even stranger is that adding .WithTrace()
in the equivalency options has the side effect of correcting the property name and displaying the right thing.
Is it a bug, or am I missing something there?
user26719255 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.