Is there a Has-Only-One constraint in NUnit?
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开发者_Go百科 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]
How about
Assert.IsTrue(collection.Items.Count() == 1 && collection.Items.Contains(expected_item));
Why it is not suffice for you?
I think the best way to verify that there is only one item in the collection, and it verifies the condition is to do something like:
Assert.That(collection.Items, Has.Count.EqualTo(1).And.All.EqualTo(expected_item));
That's how you'd get the best error message in case of failure. The second best way would be @BubbleWrap's edited answer, which does the assertion job but would get the same error whether your collection has more than one item or the item is not the expected one.
If Items property has an indexer you could use
Assert.AreEqual(collection.Items[0], expected);
精彩评论