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));
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!!!
Based upon the data in your example, noting that name
is equal where Id
is equal, you could use:
var distinctLocations = collection.select(item => item.location).Distinct();
Assert.That(distinctLocations, Has.Exactly(1).Items);
If that assumption is incorrect, you would of course need to extract just the id
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.