简体   繁体   English

NUnit C# 通用 Class 测试夹具与构造函数 arguments 在 class 被测

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

I have a bunch of classes implementing an interface and having a constructor argument.我有一堆实现接口并具有构造函数参数的类。

For this classes i want to write a test with Generic Test Fixture pattern as documented in the nunit docs section: https://docs.nunit.org/articles/nunit/writing-tests/attributes/testfixture.html#generic-test-fixtures对于此类,我想使用通用测试夹具模式编写测试,如 nunit 文档部分所述: https://docs.nunit.org/articles/nunit/writing-tests/attributes/testfixture.html#generic-test-固定装置

Sample Classes i want to test:我要测试的示例类:

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

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

TestClass:测试类:

[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()
    {
        ...
    }
}

How am i able to pass the necessary constructor arguments to TClasses?我如何能够将必要的构造函数 arguments 传递给 TClasses?

You could use Activator.CreateInstance for that case.对于这种情况,您可以使用Activator.CreateInstance

It should look something like:它应该看起来像:

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

You have already an interface that does abstract every concrete implementation of that - why do you need a generic?你已经有一个接口,它确实抽象了它的每个具体实现——为什么你需要一个通用的?

May be like this:可能是这样的:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM