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
- The data source must be a member of the class containing the Theory.
- The element type must exactly match the parameter type - no implicit conversions are performed.
- Multiple
DatapointSourceattributes of the same type are combined. - Use
Datapointwhen you only need to provide a single value from a field. - The obsolete
DatapointsAttributewas replaced byDatapointSourceAttributein earlier versions.