c# - 在 ValueSourceAttribute 上指定的 sourceName 必须引用非 null 静态字段、属性或方法

标签 c# unit-testing testing nunit testcase

我正在尝试使用 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.

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

最佳答案

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

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

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

关于c# - 在 ValueSourceAttribute 上指定的 sourceName 必须引用非 null 静态字段、属性或方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46808460/

相关文章:

c# - 在表单中的 tabcontrol 中与用户控件进行通信

android - 有没有一种方法可以用 Robolectric 测试拾取器?

java - SonarQube 问题 "Add at least one assertion to this test case"用于带有断言的单元测试?

testing - VUE CLI 3 - 使用 Mocha + webpack 测试单文件组件

testing - 字母数字会包含 _ 和空格吗?

在没有 FPGA 的情况下测试我的 HDL 代码(Verilog/VHDL)?

c# - 如何使用 Entity Framework 从另一个类返回 ID 或全部?

c# - 如何从根 url 重定向到/swagger/ui/index?

c# - 您的数据访问类是什么样的?

java - 如果静态类被模拟出来,为什么 PowerMock 会尝试加载 server.xml 文件?