Search Results for

    Show / Hide Table of Contents

    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

    1. The Items keyword is required when counting total items (no constraint). It's optional when a constraint follows.
    2. Has.Exactly(0) is useful for asserting that no items match a condition.
    3. For simple count/length checks, consider using PropertyConstraint with Has.Count or Has.Length.

    See Also

    • AllItems Constraint - All items must match
    • SomeItems Constraint - At least one item matches
    • Property Constraint - Test Count or Length properties directly
    • Edit this page
    In this article
    Back to top Generated by DocFX | Copyright (c) 2018- The NUnit Project - Licensed under CC BY-NC-SA 4.0