Question

I have a simple class:

public class MyClass()
{
  public string Property1 {get;set;}
  public string Property2 {get;set;}
}

Is there any way to asssert two instances of this class for equality without Equal method implementation (I guess reflection could suit well here)? I don't want to implement Equal just for tests).

Was it helpful?

Solution

See this excerpt from the official documentation: https://fluentassertions.com/introduction

You can assert the equality of entire objects by comparing their properties by name. This even works if the types of the properties differ but a built-in conversion exists (through the Convert class). As an example, consider a Customer entity from some arbitrary domain model and its DTO counterpart CustomerDto. You can assert that the DTO has the same values as the entity using this syntax:

dto.ShouldHave().AllProperties().EqualTo(customer);

As long as all properties of dto are also available on customer, and their value is equal or convertible, the assertion succeeds. You can, however, exclude a specific property using a property expression, such as for instance the ID property:

dto.ShouldHave().AllPropertiesBut(d => d.Id).EqualTo(customer);

Which is equivalent to:

dto.ShouldHave().AllProperties().But(d => d.Id).EqualTo(customer);

The other way around is also possible. So if you only want to include two specific properties, use this syntax.

dto.ShouldHave().Properties(d => d.Name, d => d.Address).EqualTo(customer);

And finally, if you only want to compare the properties that both objects have, you can use the SharedProperties() method like this:

  dto.ShouldHave().SharedProperties().EqualTo(customer);

Obviously, you can chain that with a But() method to exclude some of the shared properties.

Additionally, you can take structural comparison a level further by including the IncludingNestedObjects property. This will instruct the comparison to compare all (collections of) complex types that the properties of the subject (in this example) refer to. By default, it will assert that the nested properties of the subject match the nested properties of the expected object. However, if you do specify SharedProperties, then it will only compare the equally named properties between the nested objects. For instance:

dto.ShouldHave().SharedProperties().IncludingNestedObjects.EqualTo(customer);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top