在 Nunit SetUpFixture 类中定义一个全局变量

本文关键字:一个 全局变量 定义 Nunit SetUpFixture | 更新日期: 2023-09-27 18:35:29

嗨,我必须在使用 Nunit 进行的所有测试中使用变量

SimpleContainer container = new SimpleContainer();  

所以我尝试将此定义放在安装程序类中:

[SetUpFixture]
public static class TestSetup
{
    public static SimpleContainer container = new SimpleContainer();    
}

我使用静态类来编写:

IMyClass myClassExpected = (IMyClass)TestSetup.container.GetInstance(typeof(IMyClass), null);

但是运行测试后我收到此错误:"TestSetup是一个抽象类"

我根本不明白问题出在哪里

在 Nunit SetUpFixture 类中定义一个全局变量

我建议你不要为静态实例而烦恼,而是使用继承。

因此,创建一个基类,其中包含您的对象:

public class BaseTestFixture
{
    public SimpleContainer Container { get { return new SimpleContainer(); } }
}   

让所有测试都继承自以下内容:

public class GoogleTests : BaseTestFixture
{
    [Test]
    public void GoToGoogle()
    {
        Container.GetInstance(.....);
    }
}   

您正在将测试夹具声明为静态。因此,NUnit无法创建它的实例并为您提供错误。只需将其更改为

[SetUpFixture]
public class TestSetup
{
    ...

我可能误解了这一点,但是您可以声明一个类变量,并且可以在构造函数中进行任何赋值。这是在TestFixture类中,而不是SetUpFixture类中。