Search Results for

    Show / Hide Table of Contents

    SomeItems Constraint

    SomeItemsConstraint applies a constraint to each item in an IEnumerable, succeeding if at least one item satisfies the constraint. An exception is thrown if the actual value does not implement IEnumerable.

    Usage

    Has.Some.<constraint>
    Has.Member(object expected)
    Contains.Item(object expected)
    Does.Contain(object expected)
    

    Modifiers

    .IgnoreCase
    .IgnoreWhiteSpace              // NUnit 4.2+
    .Using(IComparer comparer)
    .Using(IEqualityComparer comparer)
    .Using<T>(IComparer<T> comparer)
    .Using<T>(IEqualityComparer<T> comparer)
    .Using<T>(Comparison<T> comparer)
    .Using<T>(Func<T, T, bool> comparer)
    .UsingPropertiesComparer()     // NUnit 4.1+
    

    Examples

    [Test]
    public void SomeItemsConstraint_Examples()
    {
        int[] numbers = { 1, 2, 3, 4, 5 };
        string[] names = { "Alice", "Bob", "Carol" };
    
        // At least one item must satisfy the constraint
        Assert.That(numbers, Has.Some.GreaterThan(3));      // At least one > 3
        Assert.That(numbers, Has.Some.EqualTo(3));          // Contains 3
        Assert.That(names, Has.Some.Length.EqualTo(3));     // At least one 3-char name
    
        // Collection membership (all equivalent)
        Assert.That(numbers, Has.Member(3));
        Assert.That(numbers, Contains.Item(3));
        Assert.That(numbers, Does.Contain(3));
        Assert.That(numbers, Has.Some.EqualTo(3));
    
        // Custom comparison for membership
        Assert.That(names, Has.Some.EqualTo("alice").IgnoreCase);
        Assert.That(names, Has.Some.EqualTo("bob").Using(StringComparer.OrdinalIgnoreCase));
    }
    

    Contains examples

    [Test]
    public void CollectionContains_Examples()
    {
        int[] intArray = [1, 2, 3];
        string[] stringArray = ["a", "b", "c"];
    
        Assert.That(intArray, Has.Member(3));
        Assert.That(stringArray, Has.Member("b"));
        Assert.That(stringArray, Contains.Item("c"));
        Assert.That(stringArray, Has.No.Member("x"));
        Assert.That(intArray, Does.Contain(3));
    }
    

    Notes

    1. Has.Member(), Contains.Item(), and Does.Contain() are all equivalent to Has.Some.EqualTo().
    2. The constraint succeeds as soon as the first matching item is found.
    3. An empty collection always fails this constraint.
    4. For testing substring containment in strings, see SubstringConstraint.

    See Also

    • AllItems Constraint - All items must match
    • NoItem Constraint - No items match
    • Contains Constraint - Polymorphic containment testing
    • 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