Is sharing the instance of Fixture
across multiple test methods a good practice?
Or is it better to create a new instance of Fixture
for every test method?
What is the best practice? It will be good if you can provide me with a source on which one is anti-pattern.
AutoFixture takes its name from the Fixture pattern:
"a test fixture is all the things we need to have in place in order to run a test and expect a particular outcome. [...] Setting up the test fixture is the first phase of the Four-Phase Test."
While a Shared Fixture is a conceptual possibility, it comes with lots of disadvantages, because it makes it harder to make tests independent of each other.
AutoFixture was explicitly designed to provide a reusable library for creating Fixtures, instead of having to manually code Fixture Objects for every new kind of test context you'd need to create.
There are people who create a single (AutoFixture) Fixture
object and share it across multiple test methods, but I never understood why they do that; it almost defeats the purpose of AutoFixture.
Still, if you find such a set-up useful, who am I to tell you to stop doing it? Whatever floats your boat... However, AutoFixture was designed with the explicit use case of one Fixture
instance per test method in mind, and I haven't seen any advantages to doing it the other way.
The best practice is to take advantage of AutoFixture.Xunit or AutoFixture.NUnit2 and avoid creating a Fixture
instance, inside or outside of the test methods or functions.
If you can't use any of the above Glue Libraries, it is considered a good practice when using a new instance of the Fixture
class in each test.
Using a new instance of the Fixture
class allows you to control how AutoFixture behaves on each particular test, as you may apply Customizations to it, and they are not going to affect all the other tests.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With