fluentassertions.analyzers
fluentassertions.analyzers copied to clipboard
Analyzer incorrectly recommends ContainsSingle for HaveCount(1).And.Contains()
Description
Analyzer incorrectly recommends ContainsSingle()
for HaveCount(1).And.Contains(predicate)
but looking at the tests for ContaiansSingle they are not equivalent as shown by this test https://github.com/fluentassertions/fluentassertions/blob/501cf353ecc872154fae54960ee1b692851bfb8a/Tests/FluentAssertions.Specs/Collections/GenericCollectionAssertionsSpecs.cs#L302-L314 which passes when a collection has multiple elements with only one matching the predicate.
Complete minimal example reproducing the issue
Complete means the code snippet can be copied into a unit test method in a fresh C# project and run. Minimal means it is stripped from code not related to reproducing the issue.
// Arrange
IEnumerable<int> collection = new[] { 1, 2, 3 };
// Assert
collection.Should().HaveCount(1).And.Contains(i => i == 1 ); // This would fail
collection.Should().ContainSingle(i => i == 1 ); // This would pass
Expected behavior:
No analyzer recommendation
Actual behavior:
Analyzer recommends using ContainsSingle
Versions
Fluent Assertions 0.11.4 .Net 5
@AquilaSands is this an actual use-case? I think a better syntax would be
collection.Should().ContainSingle().Which.Should().Be(1);
It was an actual use case for me but I agree the Which().Should().Be()
is better, would it be possible for the analyzer to detect the And.Contain()
and recommend the better syntax?
@AquilaSands I think so. I'll take a look