Billy ONeal
Billy ONeal

Reputation: 106530

Can I have code that executes before and after tests are run by NUnit?

I've got a bunch of tests in NUnit which create garbage data on the filesystem (bad, I know, but I have little control over this). Currently we have a cleanup tool that removes these temporaries and such, but I'd like to be able to run that cleanup tool automatically. I'd have to be able to run it after all tests have finished running. I have similar checking that I'd like to do at the beginning, to ensure that there are none of these temporaries left from previous runs that might change the outcome of the tests.

Is such a thing simple or am I going to have to implement a whole new test runner for such a thing?

Upvotes: 15

Views: 12170

Answers (3)

ChrisF
ChrisF

Reputation: 137108

Yes,

Use the [SetUpFixture] attribute on a class and the [SetUp] and [TearDown] attributes on methods with that class.

The SetUp method in a SetUpFixture is executed once before any of the fixtures contained in its namespace. The TearDown method is executed once after all the fixtures have completed execution. In the examples below, the method RunBeforeAnyTests() is called before any tests or setup methods in the NUnit.Tests namespace. The method RunAfterAnyTests() is called after all the tests in the namespace as well as their individual or fixture teardowns have completed exection.

Source

Upvotes: 24

driis
driis

Reputation: 164281

Yes, use SetupFixture attribute on a class, and use [SetUp] for initializing before tests are run and [TearDown] for cleaning up afterwards.

Upvotes: 1

ThatBlairGuy
ThatBlairGuy

Reputation: 2462

Take a look at TestFixtureSetUp and TestFixtureTearDown.

Upvotes: 4

Related Questions