Why doesn't NUnit have IsElementOf / IsOneOf restrictions?

I do not work directly with NUnit, but I want to borrow some of his ideas in a different context.

One particularly elegant idea is a constraint mechanism that allows you to write unit test forms:

Assert.That(aValue, Is.GreaterThan(2.0) & Is.LessThan(5.0));

You can also check that the value is in a certain range:

Assert.That(aValue, Is.InRange(2.0, 5.0));

However, there seems to be no way to verify what aValueis one of a set of valid values:

Assert.That(aValue, Is.OneOf(aCollection));

Isn't that so common in unit test? Indicates some issues with my unit tests? Does everyone just inject aValue into some kind of dummy collection of elements and then use it Is.SubsetOf?

+5
source share
2

@Lambdageek;

Assert.That(aCollection, Has.Member(aValue) 
Assert.That(aCollection, Has.No.Member(aValue) 

. , - .

, - . , .

    [Test]
    public void Test() {
        var c = new[] {"one", "two"};
        Assert.That(c, Has.Member("three"));
    }

Test failed:
  Expected: collection containing "three"
  But was:  < "one", "two" >
    Tests.cs(73,0): at ...Test()

Cheers,
Berryl

public static class TestExtensions
{
    public static bool IsOneOf<T>(this T candidate, IEnumerable<T> expected) {
        if (expected.Contains(candidate)) return true;

        var msg = string.Format("Expected one of: '{0}'. Actual: {1}", ", "._insertBetween(expected.Select(x => Convert.ToString(x))), candidate);
        Assert.Fail(msg);
        return false;
    }

    private static string _insertBetween(this string delimiter, IEnumerable<string> items)
    {
        var builder = new StringBuilder();
        foreach (var item in items)
        {
            if (builder.Length != 0)
            {
                builder.Append(delimiter);
            }
            builder.Append(item);
        }
        return builder.ToString();
    }

    internal static IEnumerable<string> GenerateSplits(this string str, params char[] separators)
    {
        foreach (var split in str.Split(separators))
            yield return split;
    }

}

    [Test]
    public void IsOneOf_IfCandidateNotInRange_Error()
    {
        IEnumerable<string> expected = new[] { "red", "green", "blue" };
        const string candidate = "yellow";
        Assert.That(candidate.IsOneOf(expected));
    }

IsOneOf_IfCandidateNotInRange_Error' failed:
Expected one of: 'red, green, blue'. Actual: yellow
+1

API , , Is.OneOf(collection):

Assert.That(collection.Contains(value));

, API , . , Is.InRange, Is.GreaterThan + Is.LessThan ,

Assert.That(value > 2.0 && value < 5.0);
//compared to
Assert.That(value, Is.GraterThan(2.0).And.Is.LessThan(5.0));
+3

All Articles