Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

Sample Classes i want to test:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

You could use Activator.CreateInstance for that case.

It should look something like:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading