首页 > 解决方案 > C# NUnit 报告奇怪的错误:“没有找到合适的构造函数”

问题描述

我正在使用 VS2019 并使用 .NET Core 模板创建了一个 NUnit 测试项目,然后我添加了以下代码:

using NUnit.Framework;

namespace xxx
{
    class Immutable
    {
        public Immutable(string _cur, string _addr)
        {
            Currency = _cur;
            Address = _addr;
        }

        public string Currency { get; }
        public string Address { get; }

        [Test]
        public static void Test() // reports this line has problem?
        {
            var m = new Immutable("usd", "us");
            string s = m.Currency;
            Assert.AreEqual("usd", s);
        }
    }
}

构建好,但是当我运行它时,测试资源管理器会报告这个:

Test
Source: xxx.cs line 17
Duration: < 1 ms

Message: 
    OneTimeSetUp: No suitable constructor was found

我不太明白问题是什么,如何解决?

标签: c#unit-testing.net-coreconstructor

解决方案


如果您的测试类具有参数化构造函数,则需要带有参数的 TestFixture 属性来构造它。

尝试这个:

[TestFixuture("usd", "us")]
class Immutable
{
    ...
}

文件

并强烈建议您单独一个测试类进行测试。

[TestFixture]
public class ImmutableTest
{
    [Test]
    public void Test()
    {
        var m = new Immutable("usd", "us");
        string s = m.Currency;
        Assert.AreEqual("usd", s);
    }
}

推荐阅读