Is there a Has-Only-One limitation in NUnit?

Recently, I really need this logic:

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 is the best way to accomplish this without two statements?

+6
unit-testing nunit
source share
4 answers

Starting with NUnit 2.6 (not at request time):

 Assert.That(collection.Items, Has.Exactly(1).EqualTo(expected_item)); 

Has.Exactly "Applies a limit on each item in the collection if the specified number of items is executed." [one]

+3
source share

You can 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 does not contain exactly 1 item.

I am not familiar with NUnit, so someone can suggest a better solution that uses the NUnit function ...

EDIT: after a quick search, the only NUnit function that seems to be approaching is Is.EquivalentTo(IEnumerable) :

 Assert.That(collection.Items, Is.EquivalentTo(new List<object>() {expected_item})); 

IMO the first option reads me better, but the latter may give a better exception message depending on your preference.

+10
source share

What about

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

Why is this not enough for you?

+3
source share

If the Items property has an index, you can use

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

All Articles