Sharing AutoFixture across tests
Asked Answered
B

2

8

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.

Bouncer answered 19/1, 2015 at 1:55 Comment(0)
P
10

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.

Purapurblind answered 19/1, 2015 at 7:30 Comment(0)
F
7

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.

Farwell answered 19/1, 2015 at 7:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.