I'm finding myself needing a lot of this sort of logic lately:
Assert.That(collection.Items, Has.Member(expected_item));
Assert.That(collection.Items.Count(), Is.EqualTo(1));
I see that NUnit offers Has.Some
and Has.All
, but I don't see anything like Has.One
. What's the best way to accomplish this without two asserts?
You could try something like this:
Assert.AreEqual(collection.Items.Single(), expected_item);
Single will return the only item in the collection, or throw an exception if it doesn't contain exactly 1 item.
I'm not that familiar with NUnit though, so someone might offer a better solution that does use an NUnit function...
EDIT: after a quick search, the only NUnit function that seems to come close is Is.EquivalentTo(IEnumerable)
:
Assert.That(collection.Items, Is.EquivalentTo(new List<object>() {expected_item}));
IMO the first option reads better to me, but the latter might give a better exception message depending on your preferences.
As of NUnit 2.6 (not around when this question was asked):
Assert.That(collection.Items, Has.Exactly(1).EqualTo(expected_item));
Has.Exactly
"Applies a constraint to each item in a collection, succeeding if the specified number of items succeed." [1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With