Skip to content

BeEquivalent failed with nullably struct property and EqualityComparer #2480

@MartinDemberger

Description

@MartinDemberger

Description

I have a complex object structure. A few properties are of a nullable struct which must be compared by my own EqualityComparer.

The BeEquivalentTo-call always fails if the struct value is null.

The EqualityComparer is necessary because not all properties of the struct should be compared and the compared values must be decrypted to be compared.

Reproduction Steps

 [Fact]
 public void FluentAssertionsTest()
 {
     var art1 = new MyTestClass();
     art1.Should().BeEquivalentTo(new MyTestClass(), o => o
     //.Using<MyProperty?, MyPropertyComparer>()
     .Using<MyProperty, MyPropertyComparer>()
     );
 }

 public class MyTestClass
 {
     public MyProperty? ArticlePriceWithOtherParts { get; set; }
 }

 public struct MyProperty
 {
     public int Value1 { get; set; }
     public int Value2 { get; set; }
 }

 public class MyPropertyComparer : IEqualityComparer<MyProperty?>, IEqualityComparer<MyProperty>
 {
     public bool Equals(MyProperty? x, MyProperty? y)
     {
         var result = Equals(x?.Value1, y?.Value1);
         return result;
     }

     public bool Equals(MyProperty x, MyProperty y)
     {
         var result = Equals(x.Value1, y.Value1);
         return result;
     }

     public int GetHashCode([DisallowNull] MyProperty? obj)
     {
         if (obj is null)
             return 0;
         return obj.Value.Value1;
     }

     public int GetHashCode([DisallowNull] MyProperty obj)
     {
         return obj.Value1;
     }
 }

Expected behavior

The test should succeed.

Actual behavior

the test fail with the message

Expected property art1.ArticlePriceWithOtherParts to be of type RootNine.ProjectNet.Tests.Calculations.TestOutgoingOfferCalculationElPro+MyProperty, but found

Regression?

No response

Known Workarounds

No response

Configuration

.NET 7.0
FluentAssertions: 6.12.0

Other information

No response

Are you willing to help with a pull-request?

Yes

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions