views:

82

answers:

3

We have a set of services in .NET 3.5\C# and WCF. The NUnit tests need the services to be running and listening for requests. The services need an updated SQL database to be ready for connection.

Currently the [SetUp] section of the unit test does two tasks:

  • Execute the latest SQL scripts to build the database.
  • Utilize a System.Diagnostics.Process.Start to run the commandline mode of the services.

It usually works but the services are sensitive for certain schema changes, which sometimes fails them. I'm looking for the best practice for setup the database and then the services, and also making sure the services are down at the end.

The process is run by MSBuild.

+1  A: 

The best practice for unit testing is using mock objects which emulate database behavior instead of the real database.

Dmitry
+4  A: 

If you're starting the services, and hitting actual executing services...changes are you're not just Unit testing anymore. You're now integration testing.

You should really think about abstracting your Data Access into an Interface. You can then code a concrete implementation of that Interface for normal operation and use Dependency Injection to inject a mock implementation for your Unit tests.

Justin Niessner
Can you elaborate on this? I mean from theory to practice - any examples I can use?
KMoraz
A: 

Have you done much with Dependency Injection (DI)?

I highly recommend reading Jerry Millers blog, he's got lots of great stuff on Unit Testing and DI using .Net.

Here's a post to get your started on The Dependency Injection Pattern.
Once you've read this, have a look at his post on Unit Testing Business Logic.

Using MSBuild is a good start, so now its a case of re factoring out the external services and then mocking them during your test. How complicated you want the mocking to be is up to you.

Here's a SO post on Mocking Frameworks to get you started.

I'd suggest breaking your testing into two separate parts:

  • Unit Testing (where you would use DI to mock out the external services)
  • Integration testing (what you are currently doing)

At the end of the tests you could stop your services using a method with the [TestFixtureTearDown] attribute.

Ralph Willgoss