NUnit C# Generic Class Test Fixtures with constructor arguments in the class under test

NUnit C# Generic Class Test Fixtures with constructor arguments in the class under test

我有一堆 类 实现接口并具有构造函数参数。

为此 类 我想使用 Generic Test Fixture 模式编写一个测试,如 nunit 文档部分所述:https://docs.nunit.org/articles/nunit/writing-tests/attributes/testfixture.html#generic-test-fixtures

样本类我想测试:

public class ClassToTest: IInterface
{
    public ClassToTest(ConstructorArgument arg1)
    {
        ....
    }
}

class AnotherClassToTest: IInterface
{
    public AnotherClassToTest(ConstructorArgument arg1)
    {
        ....
    }
}

测试类:

[TestFixture(typeof(ClassToTest))]
[TestFixture(typeof(AnotherClassToTest))]
public class TestClass<TClasses> where TClasses : IInterface, new()
{
    private IInterface _classUnderTest;

    public TestClass()
    {
        ConstructorArgument args = new();
        _classUnderTest = new TClasses(args);  //This will not compile
        //How to Pass constructor argument args?
    }

    [Test]
    public void Test1()
    {
        ...
    }
}

如何将必要的构造函数参数传递给 T类?

您可以使用 Activator.CreateInstance 来处理这种情况。

它应该看起来像:

_classUnderTest = (TClasses)Activator.CreateInstance(typeof(TClasses), new object[] { args });

您已经有了一个接口,它抽象了它的每个具体实现 - 为什么您需要一个泛型?

可能是这样的:

[TestFixture(new ClassToTest(new ConstructorArgument()))]
[TestFixture(new AnotherClassToTest(new ConstructorArgument()))]
public class TestClass
{
    private IInterface _classUnderTest;

    public TestClass(IInterface classUnderTest)
           : _classUnderTest(classUnderTest)
    {}
}