Search code examples
c#unit-testingtestingnunittestcase

The sourceName specified on a ValueSourceAttribute must refer to a non null static field, property or method


I am trying to use ValueSourceAttribute for my tests.

Here is an example

  [Test]
        public async Task TestDocumentsDifferentFormats(
            [ValueSource(nameof(Formats))] string format,
            [ValueSource(nameof(Documents))] IDocument document)
        {

The interesting thing is that Formats list (first argument) works perfectly, however it cannot resolve second argument, even if it defined in the same way.

Here is how I defined Documents static list

  public class DocumentFactory
    {
        public static readonly List<IDocument> Documents=
            new List<IDocument>
            {
              // Init documents
            };
    }

But when I try to run my tests it throws an error.

The sourceName specified on a ValueSourceAttribute must refer to a non null static field, property or method.

What can cause this problem ? I would be grateful for any help.


Solution

  • If values are defined in another class you should provide it's type too as parameter for attribute

    [Test]
    public void TestOne(
        [ValueSource(nameof(Formats))] string format, 
        [ValueSource(typeof(DocumentFactory), nameof(DocumentFactory.Documents))] IDocument document)
    {
            document.Should().NotBeNull();
    }
    

    Without providing a type, NUnit will use type of current class as default type, that is why Formats works.