Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert that all items in a collection have the value for one of the items property using NUnit

I have to convert MS unit tests to NUnit and came across this assertion.

Assert.AreEqual(collection.Select(item => item.location.id).Distinct().Count(), 1);

I was hoping the there would be an elegant way to write that with constraints but I have not been able to find one. My solution is this, but Im not that happy with it:

Expect(collection.Select(item => item.location.id).Distinct().Count(), Is.EqualTo(1));

Is there a better way of writing that assertion where the intent is clearer readable? (Using Has. or Map(collection). )


Edit 2:

I just realized it may be helpful to clearly state what the intent is:

all items in the collection have the same location ID (without knowing what that ID is)


Edit 1:

This is what the collection may look like as JSON:

[{itemId=1, location={name="A", id=1}},
 {itemId=2, location={name="A", id=1}},
 {itemId=3, location={name="A", id=1}}]

distinct.count = 1     => pass

[{itemId=1, location={name="A", id=1}},
 {itemId=2, location={name="A", id=1}},
 {itemId=4, location={name="B", id=2}}]

distinct.count = 2     => fail

Edit 3: my final solution, based on Fabio's answer

IEnumerable<long?> locationIds = collection.Select(item => item.location.id);
Expect(locationIds, Has.All.EqualTo(locationIds.FirstOrDefault()));
like image 608
Holly Avatar asked Aug 09 '16 12:08

Holly


2 Answers

Readable version

int expectedCount = 1;
int actualCount = collection.Select(item => item.location.id)
                            .Distinct()
                            .Count()

Assert.AreEqual(expectedCount, actualCount);

I am not sure but you can try this version, where phrase "Is all equal to..." must help to "non-programmers" and your code get rid of "magic" numbers

var value = collection.Select(item => item.location.id).FirstOrDefault();
Assert.That(collection.Select(item => item.location.id), Is.All.EqualTo(value));
like image 133
Fabio Avatar answered Sep 22 '22 13:09

Fabio


If I've understood what you want to do... this should do it...

Assert.That(collection.Select(() => item.location.id), Is.Unique);

Leaving this wrong answer here... somebody may want to test uniqueness, but that's not what this guy wanted!!!

like image 26
Charlie Avatar answered Sep 20 '22 13:09

Charlie