views:

25

answers:

1

I am toying with the idea of unit testing a tier within my application using the Mock Object Pattern. The problem i'm facing is how to switch from my mock objects to the real objects when not unit testing.

My initial reaction was to reference two libraries (one containing the real objects and one with the mocks) and use conditional compilation symbols to switch between the two namespaces. This however clearly requires that the project be rebuilt without the UNITTEST symbol (after passing unit-testing) in order for the real objects to be re-referenced.

Are there any patterns which achieve this goal?

FYI, my environment is c# 2 if that provides any benefit.

+7  A: 

You'll want to look up dependency injection and the way objects should accept their dependencies via the constructor instead of creating them themselves.

For example, contrast:

public MyClass()
{
    myDBConnection = new SqlConnection();
}

vs

public MyClass(IDbConnection connection)
{
    myDBConnection = connection;
}

In the second you could pass a mock database connection in your unit test, in the real code you pass the real thing.

Paolo