Tutorial :Pattern for switching a project from using mock objects and real objects



Question:

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.


Solution:1

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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »