views:

52

answers:

3

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?

+8  A: 

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.

Bubblewrap
Good answer. I do still wonder if there isn't a constraint hiding in there somewhere that does what I want, though.. it seems natural enough, no?
ladenedge
Well not really natural, as a list naturally contains any amount of items, and if you're expecting only one, it defeats the purpose of a list :)
PostMan
+2  A: 

How about

Assert.IsTrue(collection.Items.Count() == 1 && collection.Items.Contains(expected_item));

Why it is not suffice for you?

Anindya Chatterjee
+2  A: 

If Items property has an indexer you could use


Assert.AreEqual(collection.Items[0], expected);

sh_kamalh
Doesn't confirm that there is exactly one item
PostMan
You are correct. I missed that.
sh_kamalh