Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 see anything like Has.One. What's the best way to accomplish this without two asserts?

like image 893
ladenedge Avatar asked Sep 28 '10 15:09

ladenedge


2 Answers

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.

like image 108
Bubblewrap Avatar answered Sep 22 '22 14:09

Bubblewrap


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]

like image 30
Seb Wills Avatar answered Sep 21 '22 14:09

Seb Wills