Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading