Valentin Kuzub
Valentin Kuzub

Reputation: 12073

Does NUnit create a new instance of the test fixture class for each contained test method nowadays?

As written in a fairly old book XUnit Patterns NUnit 2.0 did not create new test fixtures for each test, and because of that if tests were manipulating some state of fixture it became shared and could cause various bad side effects.

Is this still the same? I tried to find it on official site but failed, and havent used NUnit for a while.

Upvotes: 29

Views: 5979

Answers (3)

Alexander Bartosh
Alexander Bartosh

Reputation: 8797

Since 3.13 you can configure that with

LifeCycle.SingleInstance    A single instance is created and shared for all test cases
LifeCycle.InstancePerTestCase   A new instance is created for each test case

https://docs.nunit.org/articles/nunit/writing-tests/attributes/fixturelifecycle.html

Upvotes: 11

Dave
Dave

Reputation: 317

I found that this was an issue that affected me and also found this link which provides a bit of history to the issue; https://blogs.msdn.microsoft.com/jamesnewkirk/2004/12/04/why-variables-in-nunit-testfixture-classes-should-be-static

I think one of the biggest screw-ups that was made when we wrote NUnit V2.0 was to not create a new instance of the test fixture class for each contained test method.

Not yet tested this in V3 to see if its changed

Upvotes: 6

Pedro
Pedro

Reputation: 12328

The fixture is created once for all of the tests in that fixture.

For a given fixture class, a FixtureSetup method is run once for all of the tests in a fixture, and a Setup method is run once for each test. So, any state that needs to be reset should be done in a Setup method (or TearDown, which is run at the end of each test.)

Upvotes: 22

Related Questions