Don’t do anything that might throw an exception in a TestFixture
constructor: your tests will be ignored, rather than failing.
My colleague Chris and I have been playing around with polymorphous testing, taking advantage of the fact that you can pass parameters to an NUnit TestFixture
like this:
[TestFixture(parameter1)] [TestFixture(parameter2)] public class BazTests{ public BazTests(Blah parameter){ ... } }
We wanted to use these parameters to pass in a collaborator, which would then enable us to run the same tests against different implementations of the same interface. However, we immediately encountered difficulties, as the TestFixture
attribute will only take parameters that are compile-time constants, which rules out directly passing in a collaborator class. If you are adding parameters to a Test
, you can use the TestDataSource
attribute to pass in more complex arguments; however, no such attribute is available for TestFixture
s.
To get round this, we created a static factory that would then create our dependency according to the enum value passed in:
[TestFixture(TestSetting.Foo)] [TestFixture(TestSetting.Bar)] public class BazTests{ private ITestHelper _testHelper; public BazTests(TestSetting testSetting){ _testHelper = TestHelperFactory.Create(testSetting); } }
However, some of our implementations of ITestHelper
require a connection string, and when it is not present, a NullReferenceException
is thrown. We would have expected some of our tests to fail because of this, but instead they were just ignored, and as TeamCity disregards ignored tests, this meant that our builds were treated as successful.
It suspect the tests are ignored because exceptions in the test constructor are not sent to TeamCity as errors; rather the exception must happen in one of the attribute-decorated methods.
The code gave us the correct failures once we had rewritten it like this:
[TestFixture(TestSetting.Foo)] [TestFixture(TestSetting.Bar)] public class BazTests{ private TestSetting _testSetting; private ITestHelper _testHelper; public BazTests(TestSetting testSetting){ _testSetting = testSetting; } [TestFixtureSetUp] public void TestFixtureSetUp(){ _testHelper = TestHelperFactory.Create(_testSetting); } }