Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing AutoFixture across tests

Tags:

c#

autofixture

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.

like image 812
user3117252 Avatar asked Jan 19 '15 01:01

user3117252


2 Answers

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.

like image 100
Mark Seemann Avatar answered Nov 09 '22 03:11

Mark Seemann


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.

like image 43
Nikos Baxevanis Avatar answered Nov 09 '22 04:11

Nikos Baxevanis