Question

I've been using NDepend on my codebase and while my actual code seems to pass with flying colors, my unit test code could use a lot of work. One of the suggestions NDepend made was converting many of my unit test classes into static classes due to a high degree of separation between the tests. It does seem like this might help not share state between tests and allow them even further to run in any order. Should I convert my unit test classes to static classes?

Sharing state between test methods in the same TestFixture and of course between TestFixtures

Was it helpful?

Solution

Intriguing! I've never seen anyone apply NDepend analysis to test projects before. While unit tests should be considered first class citizens of your code base, they aren't typically deployed with the application and as such aren't viewed with the same architectural constraints (FxCop, NDepend, etc). On some level I agree with this approach, the quality of the tests need to be validated, but I can't see what benefit a tool can provide here other than identifying class coupling concerns that would also be identified in the production code.

Regarding NUnit, it typically instantiates a single instance of the testfixture for all test methods in that test class. State is shared between tests, and that's good and bad.

Good: state that takes time to create can be set up when the test fixture is set up.

Bad: state that should be reset between tests is up to you to fix between tests.

If NUnit supports static methods for tests and if you need any state within the test fixture those fields are going to need to be static. That's actually really scary because state of your tests is shared for the lifetime of the test appDomain.

The key is to use the NUnit attributes for fixture and test initialization / teardown. Never use constructors or finalizers for fixture initialization as you can't control when the NUnit framework creates your class.

OTHER TIPS

If your tests don't need to run in a particular order or they don't depend on initializer code you can make them static.

Do remember that this is not a recipe for success though.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top