Search Results for

    Show / Hide Table of Contents

    DatapointSource

    DatapointSourceAttribute is used to mark a field, property, or method as providing a collection of data values for Theory tests. The source must return either an array of the required type or an IEnumerable<T>.

    This attribute is ignored for ordinary tests, including parameterized tests using [TestCase].

    Usage

    This is a parameterless attribute that can be applied to fields, properties, or methods.

    [DatapointSource]
    

    Applies To

    Field Property Parameterless Methods Test Methods Test Fixtures (Classes) Assembly
    ✅ ✅ ✅ ❌ ❌ ❌
    Note

    Parameterless methods used with this attribute must return an array or IEnumerable<T>, and the element type must exactly match the Theory parameter type.

    Example

    [TestFixture]
    public class PrimeNumberTests
    {
        // DatapointSource on a field returning an array
        [DatapointSource]
        public int[] SmallPrimes = { 2, 3, 5, 7, 11, 13 };
    
        // DatapointSource on a property returning IEnumerable<T>
        [DatapointSource]
        public IEnumerable<int> MorePrimes
        {
            get
            {
                yield return 17;
                yield return 19;
                yield return 23;
            }
        }
    
        // DatapointSource on a method
        [DatapointSource]
        public int[] GetPrimesUnder100()
        {
            return new[] { 29, 31, 37, 41, 43, 47 };
        }
    
        [Theory]
        public void PrimeIsOddOrTwo(int prime)
        {
            // NUnit combines all datapoint sources for int type
            Assert.That(prime == 2 || prime % 2 != 0);
        }
    }
    

    Automatically Supplied Datapoints

    NUnit automatically supplies datapoints for certain types:

    Type Automatic Values
    bool true, false
    Any enum All defined enum values

    If you supply any datapoints for a parameter type, automatic datapoint generation for that type is suppressed.

    Notes

    1. The data source must be a member of the class containing the Theory.
    2. The element type must exactly match the parameter type - no implicit conversions are performed.
    3. Multiple DatapointSource attributes of the same type are combined.
    4. Use Datapoint when you only need to provide a single value from a field.
    5. The obsolete DatapointsAttribute was replaced by DatapointSourceAttribute in earlier versions.

    See Also

    • Datapoint Attribute
    • Theory Attribute
    • Parameterized Tests
    • 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