【问题标题】:Resolving NUnit "No suitable constructor was found" message解决 NUnit “未找到合适的构造函数”消息
【发布时间】:2018-11-20 18:32:41
【问题描述】:

我有一个单元测试类:

[TestFixture]
public class SomeClassIntegrationTests : SomeClass

使用公共构造函数:

public SomeClassIntegrationTests (ILogger l) : base(l)
{
}

当我尝试运行测试时,出现“未找到合适的构造函数”错误。

我尝试将TestFixture 属性更改为[TestFixture(typeof(ILogger))],但它导致相同的错误消息不允许我运行或调试测试。

知道如何修改TestFixture 属性以使测试运行或以其他方式解决此问题吗?

【问题讨论】:

  • 要让[TestFixture(typeof(ILogger))]工作,你需要一个构造函数SomeClassIntegrationTests(Type)。
  • @KlausGütter 这不是一个有效的构造函数,因为 SomeClassIntegrationTests 继承自 SomeClass。
  • 我最终在基类和测试类中创建了一个无参数构造函数,解决了“找不到合适的构造函数”问题,但如果有人知道 TestFixture 属性应该如何,我会留下问题在这种情况下进行了修改。
  • 你不能。属性参数必须是以下类型之一的常量:bool、byte、char、double、float、int、long、sbyte、short、string、uint、ulong、ushort、System.Type、enum、这些类型的数组。无法将 ILogger 指定为属性参数。请参阅我的答案以了解可能的替代方案。

标签: c# unit-testing nunit nunit-2.5


【解决方案1】:

您可能需要一个实现 ILogger 的类的实例。

选项 1:使用 null(如果不需要记录器):

[TestFixture(null)]

选项 2:始终使用相同的具体类(或模拟):添加无参数构造函数

SomeClassIntegrationTests()
: this(new MyLogger())
{
}

和

[TestFixture]

选项 3:您可能希望使用不同的记录器进行测试

SomeClassIntegrationTests(Type t)
: this((Ilogger)Activator.CreateInstance(t))
{
}

和

[TestFixture(typeof(MyLogger))]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 2016-03-24
    • 2018-01-12
    • 1970-01-01
    相关资源
    最近更新 更多