views:

70

answers:

2

We need some global one time setup code in our test suite. We can do it more than once but it takes quite some time.

  • It's required by all fixtures so [TestFixtureSetUp] does not work. It has to run before all [TestFixtureSetUp] code.

  • Put it in Main() since we keep test assemblies as executables. However Main doesn't get executed under GUI client.

  • Creating a separate class with a static constructor for initialization only works when you reference the class which we do not favor doing in each and every class.

  • Inheriting all test fixtures from a base class and adding a static constructor to it causes multiple calls to the init code.

Now given the circumstances, I have two questions:

1) Is "global setup" a very bad idea that it's not supported by NUnit?

2) What's the least painful, most common way to achieve this?

+1  A: 

1) I guess it depends on the context. I've never needed a global setup on any project, but I can imagine scenarios, e.g. an app that only reads data, and a common, global data setup.

2) You could make your global setup, e.g. in the fixture base you mention, stateful. I.e. have a HasRun property or the like that is checked before execution.

Martin R-L
+2  A: 

I don't think there is a nice, built in way to achieve it unfortunately - probably because NUnit is meant to be used for unit tests mainly, and you shouldn't need any global setup for unit tests (everything should be locally mocked in every test fixture).

It is however quite common to use NUnit for integration tests, and there it is very common to have a global setup - as in your case. There are a few reasonable options here:

  1. On my current project we usually do in in the msbuild script that is running the tests. The benefits are that you don't need to remember about any special setup when you write new tests. The downside - you have to make sure you have everything set up when you run the tests from IDE.

  2. If the above is not an option you can use your last idea - to inherit the tests from a common base class. The base class could then reference a singleton class (you can find i.e. Jon Skeets article on how to implement a singleton), which would do the setup. This way it will be run only once.

Grzenio