Search code examples
c#fluent-assertions

Compare 2 not identical DTO but have common properties in Fluent Assertion


I am writing a unit test for a manual mapper. It maps an object to two different classes but have common properties. how to compare if their properties are equal in fluent assertion?

This is what I tried

 var domain = new Domain.ConsentDefinition()
{
     SomeProperty = 1,
     ListOfFirstDTO = new List<FirstDTO>()
     {
          new FirstDTO()
          {
             Name = "Label",
             Age = 18,
          }
     },
     SomeOtherProperty = "one"
}

ef = domain.ToEF();

domain.SomeProperty.Should().Be(ef.SomeProperty);
domain.SomeOtherProperty.Should().Be(ef.SomeOtherProperty);
domain.ListFirstDTO.Should().Equal(ef.ListOfSecondDTO); // This is NOT working

classes

public class FirstDTO
{
   public string Name {get;set;}
   public int Age {get;set;}
}

public class SecondDTO
{
   public string Name {get;set;}
   public int Age {get;set;}
   public string Email {get;set;}
}

Solution

  • Override firstDTO's equals so you compare values instead of references:

    
            public override bool Equals(object obj)
            {
                if (obj == null || !(obj is FirstDTO) || !(obj is SecondDTO))
                {
                    return false;
                }
                
                if(obj is SecondDTO){
                  return (this.Name == ((SecondDTO)obj).Name)
                    && (this.Age == ((SecondDTO)obj).Age)
    
                }
                // if obj is instance of FirstDTO check the rest of fields...
            }
    
    

    and run again

     domain.ListFirstDTO.Should().Equal(ef.ListOfSecondDTO); // This is NOT working
    
    

    Another more elegant solution with no need of overriding equals would be

    
    domain.ListFirstDTO.Select(c => c.Name).Should().Equal(ef.ListOfSecondDTO.Select(c => c.Name);
    
    domain.ListFirstDTO.Select(c => c.Age).Should().Equal(ef.ListOfSecondDTO.Select(c => c.Age);
    

    fluentassertion/collections