ValueSource
ValueSourceAttribute is used on individual parameters of a test method to identify a named data source for argument values.
Constructors
ValueSourceAttribute(Type sourceType, string sourceName)
ValueSourceAttribute(string sourceName)
| Parameter | Type | Description |
|---|---|---|
sourceType |
Type |
Type that provides the source member. Optional. |
sourceName |
string |
Name of source field, property, or method. |
Applies To
| Method Parameters | Test Methods | Test Fixtures (Classes) | Assembly |
|---|---|---|---|
| ✅ | ❌ | ❌ | ❌ |
Example
[Test]
public void TestUsingValueSource([ValueSource(nameof(Numbers))] int value)
{
Assert.That(value, Is.GreaterThan(0));
}
Source Requirements
- Source may be a field, non-indexed property, or parameterless method.
- Source member must be static.
- Source must return
IEnumerable(or async forms supported by NUnit). - Returned items must be compatible with the annotated parameter type.
Order of Execution
Individual test cases are executed in the order in which NUnit discovers them. This order does not follow the lexical order of the attributes and will often vary between different compilers or different versions of the CLR.
As a result, when ValueSourceAttribute appears multiple times on a parameter or when other data-providing attributes
are used in combination with ValueSourceAttribute, the order of the arguments is undefined.
However, when a single ValueSourceAttribute is used by itself, the order of the arguments follows exactly the order
in which the data is returned from the source.
Note on Object Construction
NUnit evaluates the source at the time the tests are loaded and builds the list of test cases from it. The source is not consulted again while the tests run. No communication is possible between these two phases - or between different runs - except through the parameters themselves.
The source therefore runs before any [OneTimeSetUp], [SetUpFixture] or [SetUp] method, and cannot use state
created there. It must also be repeatable: it runs once for every parameter that names it, and runners may load the
assembly more than once, so it must return the same values every time. See
Load Time and Execution Time for details.