We have written a test which looks like the following. This test requires that we have created en Equal-overload for the CodeTableItem-class:
ICollection<CodeTableItem> expectedValutaList = new List<CodeTableItem>();
expectedValutaList.Add(new CodeTableItem("DKK", "DKK"));
expectedValutaList.Add(new CodeTableItem("EUR", "EUR"));
RepoDac target = new RepoDac();
var actual = target.GetValutaKd();
CollectionAssert.AreEqual(expectedValutaList.ToList(),actual.ToList());
The test works fine, but has the unfortunate dependency to the Equality-function, meaning if I extend the CodeTableItem-class with one more field, and forgets to extend the Equals-function, the unit test still runs green, although we do not test for all fields. We want to avoid this Equality pollution (see Test Specific Equality), which has been written only to conform to the test.
We have tried using OfLikeness, and have rewritten the test in this way:
ICollection<CodeTableItem> expectedValutaList = new List<CodeTableItem>();
expectedValutaList.Add(new CodeTableItem("DKK", "DKK"));
expectedValutaList.Add(new CodeTableItem("EUR", "EUR"));
var expectedValutaListWithLikeness =
expectedValutaList.AsSource().OfLikeness<List<CodeTableItem>>();
RepoDac target = new RepoDac();
ICollection<CodeTableItem> actual;
actual = target.GetValutaKd();
expectedValutaListWithLikeness.ShouldEqual(actual.ToList());
But the test fails because the Capacity is not equal. I have written code that runs through reflection many times, and typically ended up implementing overloads for ignoring fields. Is there a way to ignore certain fields with the OfLikeness or ShouldEqual? Or is there some other way of solving this issue?
Just add the
.Without(x => x.Capacity)and the Likeness instance will ignore theCapacityproperty when comparing values.Update:
As Mark Seemann points out in his answer, what you probably want is to compare each element against each other. Here is a slightly different way that allows you to perform very flexible comparisons.
Assuming that the RepoDac class returns something like:
For each instance on the
expectedValutaListyou can create a dynamic proxy that overrides Equals using Likeness:The test below passes:
Note:
It is required to start with the
expectedinstance which contains the dynamically generated proxies (overriding Equals).You may find more information on this feature here.