Reputation: 460
Should I use keyword static with test fixture class and if yes what benefits will I get?
[TestFixture]
public static class MyClass
or
[TestFixture]
public class MyClass
Upvotes: 2
Views: 2025
Reputation: 2256
I think in software projects, non-static is preferred more. As a rule of thumb, if you do not have a good reason to make something static, do not make it static.
Upvotes: 1
Reputation: 170
Having experience in unit testing, I would highly recommend creating non-static classes for your tests. The short answer: more robust design, focusing on re-use.
We have hundreds of unit and integration tests. Many of these tests perform the same operations: creating data, executing test code, validating results, and cleaning up data. This is obviously a good candidate for re-use. We have a BaseTest class that performs a lot of this functionality, including keeping track of creating data and doing clean up.
At the same time, each test needs to perform slightly different operations: anything from different setup & initialization, to different validation after the code-under-test executes.
All this is perfect for good Object-Oriented design principles such as Inheritance and Polymorphism. And these principles are much easier to work with when using non-static methods.
As for concern over multiple tests sharing member data: the test framework resolves that by creating an instance of the class, performing the test, then destroying it. So each test runs in it's own class instance.
Upvotes: 1
Reputation: 13681
NUnit supports static fixtures as well as non-static because both are useful. It also supports static and non-static test methods.
If your fixture is non-static, NUnit will create an instance of it and use that for the tests. This allows your test to use inheritance as well as maintain state. Maintaining state can be risky if multiple tests use the same members and you expect to run tests in parallel at any time.
As a general rule, follow the same guidelines that most of us follow for helper methods in general. If something can be static, then make it so in order to avoid unneeded complexity.
Upvotes: 1
Reputation: 92
According to the documentation on TestFixture attribute test fixture class MAY BE static (or may not). So it seems that it's up to you to use static keyword or not.
Nevertheless, making your test fixtures non-static seems to be a better practise because it lets you to use inheritance in your tests. For example if you had some test fixtures with a set of common tests inside them, you could extract those tests to a parent test fixture.
Upvotes: 1