Home > Software engineering >  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

Time:04-15

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

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?

CodePudding user response:

You could use Activator.CreateInstance for that case.

It should look something like:

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

CodePudding user response:

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)
    {}
}
  • Related