fluentassertions.analyzers icon indicating copy to clipboard operation
fluentassertions.analyzers copied to clipboard

Analyzer incorrectly recommends ContainsSingle for HaveCount(1).And.Contains()

Open AquilaSands opened this issue 3 years ago • 3 comments

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 avatar May 25 '21 09:05 AquilaSands

@AquilaSands is this an actual use-case? I think a better syntax would be

collection.Should().ContainSingle().Which.Should().Be(1);

Meir017 avatar Oct 12 '21 18:10 Meir017

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 avatar Oct 14 '21 14:10 AquilaSands

@AquilaSands I think so. I'll take a look

Meir017 avatar Oct 17 '21 16:10 Meir017