Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoFixture Likeness - compare only matching properties

I want to be able to compare the two following objects for likeness using AutoFixture.SemanticComparison:

public class Object1
{
  public int a;
}

public class Object2
{
  public int a;
  public int b;
}

Now, when I do it this way:

var o1 = new Object1 { a = 1 };
var o2 = new Object2 { a = 1, b = 2};
o1.AsSource().OfLikeness<Object2>().ShouldEqual(o2);

I get the following exception: "The following members did not match: - b."

I found out that I can omit the 'b' member like this:

var o1 = new Object1 { a = 1 };
var o2 = new Object2 { a = 1, b = 2};
o1.AsSource().OfLikeness<Object2>().Without(object2 => object2.b).ShouldEqual(o2);

However, I find that this is quite cumbersome, because whenever I add a new member to class Object2, I have to correct my unit tests (or at least unit test helpers).

Is there a way to say "I want to compare for likeness just for the subset that exists in both objects"?

like image 959
Grzesiek Galezowski Avatar asked Feb 18 '12 12:02

Grzesiek Galezowski


1 Answers

It sounds like you'd like to compare two objects based on the intersection of their properties. This is not currently supported by the Likeness class. The reasoning is this:

Right now the destination type (in the above example, that would be Object2) is the decisive template upon which matching is done. This provides quite a strong statement for an assertion: every public property or field of this class must be matched.

However, a statement about matching the intersection of properties would be a very weak statement, because that intersection might be empty. This could result in False Negatives.

Even if you are TDDing and following the Red/Green/Refactor cycle and you've seen a unit test failing with such a hypothetical Likeness intersection, subsequent refactorings might turn such an assertion into a False Negative, as you remove the last property or field the two objects have in common - and you'll never notice.

However, AutoFixture is open source and all, so you're welcome to suggest this feature or send a pull request.

like image 165
Mark Seemann Avatar answered Sep 27 '22 17:09

Mark Seemann