ExactCount Constraint
ExactCountConstraint tests that an IEnumerable contains exactly a specified number of items that match an optional
constraint. An exception is thrown if the actual value does not implement IEnumerable.
Usage
Has.Exactly(int count).Items
Has.Exactly(int count).<constraint>
Examples
[Test]
public void ExactCountConstraint_Examples()
{
int[] numbers = { 1, 2, 3, 4, 5 };
string[] names = { "Alice", "Bob", "Carol" };
// Count total items
Assert.That(numbers, Has.Exactly(5).Items);
Assert.That(names, Has.Exactly(3).Items);
// Count items matching a constraint
Assert.That(numbers, Has.Exactly(2).GreaterThan(3)); // 4 and 5
Assert.That(numbers, Has.Exactly(3).LessThanOrEqualTo(3)); // 1, 2, and 3
Assert.That(names, Has.Exactly(1).Length.EqualTo(3)); // "Bob"
// Combining multiple counts
Assert.That(numbers, Has.Exactly(2).LessThan(3).And.Exactly(2).GreaterThan(3));
// Zero items matching
Assert.That(numbers, Has.Exactly(0).LessThan(0)); // No negatives
}
Notes
- The
Itemskeyword is required when counting total items (no constraint). It's optional when a constraint follows. Has.Exactly(0)is useful for asserting that no items match a condition.- For simple count/length checks, consider using PropertyConstraint with
Has.CountorHas.Length.
See Also
- AllItems Constraint - All items must match
- SomeItems Constraint - At least one item matches
- Property Constraint - Test
CountorLengthproperties directly