Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NUnit executes with alternate constructor

I have a class which has some unit tests, but when I am running tests I would like the class to be created with a different constructor. Something like this:

[TestFixture]
public class MyClass
{
    public MyClass() { /* set up for production */ }

    [TestFixtureConstructor]
    public MyClass() { /* set up for testing */ }

    [Test]
    public void FirstTest()
    {
        // assert some values
    }
}

Is this even possible?

I have considered using a static factory method for creating the class in production (with a private constructor), and a public constructor for the testing framework.

Does anyone have any other solutions?

like image 995
Nippysaurus Avatar asked Jul 09 '26 12:07

Nippysaurus


2 Answers

You don't do this.

You do not have your tests written inside the class that you use in real code; you write your tests external to the classes. I believe most testing suites have the concept of 'Teardown' and the opposite; to set up the test environment for a given execution.

like image 142
Noon Silk Avatar answered Jul 12 '26 00:07

Noon Silk


To give a quick example of silky's correct approach:

public class MyClass
{
    // ...
}

// In a different assembly:

[TestFixture]
public class TestMyClass
{
    [SetUp]
    public void SetUp()
    {
        _myClass = new MyClass();
    }

    [Test]
    public void FooReturnsTrue()
    {
        Assert.That(_myClass.Foo(), Is.True);
    }

    // more tests

    private MyClass _myClass;
}
like image 29
TrueWill Avatar answered Jul 12 '26 02:07

TrueWill