0

Say we have a class

class A
{
int num;
string str;
// more methods and data members
}

In a nunit test, how can we do something in the lines of

List<A> listA = GetUniqueValueList();
CollectionAssert.AllItemsAreUnique(listA, "ListA items should be unique.");

As far as I understand, the AllItemsAreUniqe works for lists with value types only. Also this test doesn't fail if say two A objects have exact same members.

dushyantp
  • 4,398
  • 7
  • 37
  • 59

1 Answers1

2

Equality is determined by the implementation of .Equals() which you can override. For a complex type this will not work out-of-the-box the way you envision it so you have to override it to account for your vision of "equality".

Community
  • 1
  • 1
Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
  • so you mean I override Equals in Class A to return false if say a.Num != b.Num ? This will work? – dushyantp Aug 05 '14 at 13:16
  • What if I do not own the class? Just a curiosity. Although I have access, it is advisable not to modify it. – dushyantp Aug 05 '14 at 13:17
  • 1
    Sometimes you have the possibility to also specify an `IEqualityComparer` which acts like an external `.Equals()` method, but `AllItemsAreUnique` does not provide that. If you don't want to modify the class then you *could* write a wrapper class around that and implement `.Equals()` there and use the public members while holding your class `A` as a member. But that's getting quite complex for little gain. Ideally every custom class should have a `.Equals()` and `.GetHashCode()` implementation anyway so definitely look into changing your class `A`. – Jeroen Vannevel Aug 05 '14 at 13:22