views:

69

answers:

2

Folks,

My apologies for the novice question. It's probably obvious, please don't laugh :-)

I have unit tests defined for my Visual Studio 2008 solution. These tests are defined in multiple methods, in multiple classes across several files.

I've read in a blog article that depending on the order of execution of tests is wrong; that said, I have to have a pre-execution step before any of these tests gets to run. I.e. I actually want to define an order of execution somehow - i.e. first I create the database; then I test that it's created; then the remaining 50 tests can run in arbitrary order.

Any ideas on how I can do that?

+1  A: 

I wouldn't test that the database is successfully created; I will assume that all subsequent tests will fail if it is not, and it feels in a way that you would be testing the test code.

Regarding a pre-test step to set up the database, you can do that by creating a method and decorating it with the ClassInitialize attribute. That will make the test framework execute that method prior to any other method within the test class:

[ClassInitialize()]
public static void InitializeClass(TestContext testContext) 
{ 
    // your init code here
}
Fredrik Mörk
The most important part of this ordering is the actual creation of the database, not the TESTING of the fact that it's created. As you noted, testing of that will be done by all other unit tests :-)As I mentioned, I have multiple test classes. I need this initialization logic called before ANY of the test classes is executed. So ClassInitialize() doesn't do it.
Alex
Just create the database logic in it's own class and call it in each test class use class initialize. A unit should always pass, no matter what, it should not be dependant on being the first, or the third, once your project grows surely you will want to run just some of your tests not all. Additionally, i'd consider creating a mock of your database and using that, rather than actually twesting against the db!
Paul Creasey
Totally makes sense. Thank you!
Alex
+1  A: 

Unit tests should all work standalone, and should not have dependencies on each other, otherwise you can't run a single test in isolation.

Every test that needs the database should then just create it on demand (if it's not already been created - you can use a singleton/static class to ensure that if multiple tests are executed in a batch, the database is only actually created once).

Then it won't matter which test executes first; it'll just be created the first time a test needs a database to use.

Jason Williams