Use of TestCaseSource forces a default fixture constructor
Unit testing for .NET
Brought to you by:
charliepoole
If I create a test fixture with argument parameters to TestFixtureAttribute with appropriate constructors with corresponding arguments, if also I use TestCaseSource then on running the tests NUnit complains when creating the test case arguments that there is not a default constructor in the test fixture.
Run the following test fixture:
[TestFixture(1)]
public class TestClass
{
public TestClass(int parameter)
{
}
public IEnumerable<int> Source
{
get
{
yield return 1;
}
}
[Test]
[TestCaseSource("Source")]
public void Test(int testCase)
{
Assert.Pass();
}
}
The workaround is obviously to add a default constructor but it would be nice to not have to provide one given that I am using a test fixture with parameters.
The same is true for ValueSourceAttribute.
I'm slightly concerned that a workaround by adding a default constructor may not necessarily always be a successful workaround. It depends entirely on what the framework is trying to do when this error occurs I suppose - that is to say "What is the framework trying to get from the test fixture when this error occurs, and is what it gets necessarily going to be correct if I use a default constructor when in reality each test fixture to be run requires different arguments?"
I agree that a default constructor _solely_ for this purpose could be a source of future problems. Your fixture has no way of knowing - in the constructor - whether it's being constructed for the purpose of creating the data or for the purpose of running tests.
There are two better workarounds:
1) Use a static TestCaseSource if that's possible in your case. Then nothing needs to be constructed.
2) Put the TestCaseSource in a different class
For the solution of the bug, it seems to me that NUnit should be constructing the test fixture using the provided parameters. It may be that the parameters take part in the construction of the test data.
This may end up being a feature request but I'll keep it as a bug for now so we can think about whether there is any interim (i.e. 2.5) solution to put in.
Charlie
Shouldn't a simple call to the default constructor do in the TestFixture class?
}
Ravichandran Jv
The discussion is about the TestFixture class, not the TestFixtureAttribute class.
This cannot be readily fixed in 2.5 - at least not without a major change in our addin API. I'm postponing it for resolution in 3.0. Please use one of the workarounds for 2.5.
I thought this over some more and decided not fixing it was just going to cause more
bug reports. Some large changes were involved, but it's in the source and will be released with NUnit 2.5.1.