【问题标题】:The sourceName specified on a ValueSourceAttribute must refer to a non null static field, property or method在 ValueSourceAttribute 上指定的 sourceName 必须引用非 null 静态字段、属性或方法
【发布时间】:2017-10-18 10:50:31
【问题描述】:

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

这是一个例子

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

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

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

  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.

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

【问题讨论】:

  • 您应该提到,只有在另一个类中声明Documents属性时才会出现此问题。
  • @Fabio 是的,它是在另一个类中声明的,是否有可能解决这个问题?

标签: c# unit-testing testing nunit testcase


【解决方案1】:

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

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

在不提供类型的情况下,NUnit 将使用当前类的类型作为默认类型,这就是 Formats 起作用的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多