在 ValueSourceAttribute 上指定的 sourceName 必须引用非空静态字段 属性 或方法

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

我正在尝试使用 ValueSourceAttribute 进行测试。

这是一个例子

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

有趣的是 Formats 列表(第一个参数)工作完美,但它无法解析第二个参数,即使它以相同的方式定义。

这是我定义文档静态列表的方式

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

但是当我尝试 运行 我的测试时它抛出一个错误。

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

什么会导致这个问题?如有任何帮助,我将不胜感激。

如果值在另一个 class 中定义,您也应该提供它的类型作为属性的参数

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

如果不提供类型,NUnit 将使用当前类型 class 作为默认类型,这就是 Formats 起作用的原因。