NUnit performs with an alternate constructor
I have a class that has some unit tests, but when I run the tests, I would like the class to be instantiated using a different constructor. Something like that:
[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 it possible?
I looked at using a static factory method to create a class in production (using a private constructor) and a public constructor for the testing framework.
Does anyone have any other solutions?
source to share
If you really want to, you can take a look at TestFixtureSetUp
.
Here's an introduction:
This attribute is used internally by TestFixture to provide a single set of functions that are executed once before any of the tests on the fixture are executed. There can be only one TestFixtureSetUp method in a TestFixture. If more than one is defined, TestFixture will compile successfully, but its tests will not run.
Example:
namespace NUnit.Tests
{
using System;
using NUnit.Framework;
[TestFixture]
public class SuccessTests
{
[TestFixtureSetUp] public void Init()
{ /* ... */ }
[TestFixtureTearDown] public void Dispose()
{ /* ... */ }
[Test] public void Add()
{ /* ... */ }
}
}
But you must use this with care, otherwise it will defeat the unit test goal .
source to share
To give a quick example of a silky 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;
}
source to share