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()));
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));