Mocking IDispossible with “Using”

Mocking objects is integral part of Unit Testing. The nucleus of Mocking is Dependency Injection, which allows us to inject Mock object into the code. But what happens when programmer has used the “Using” keyword ? For Example,

using(CustomDbCommand cmd = new CustomDbCommand ())
{
// Code
}
<pre>

This makes it difficult to mock DbCommand. The solution lies in deploying Factory Pattern to create our CustomDbCommand. For the purpose, I have created a IDbCommandFactory interface and its concrete solution in DbCommandFactory. It comprises of a method called CreateDbCommandObject, which returns a new instance of CustomDbCommand;

public interface IDbCommandFactory
{
CustomDbCommand CreateDbCommandObject();
}

public class DbCommandFactory : IDbCommandFactory
{
public CustomDbCommand CreateDbCommandObject()
{
return new CustomDbCommand();
}
}

Now that we have our Factory Object ready, it is time to inject it into our Repository Class. I prefer to use Constructor Injection for the purpose.


private readonly IDbCommandFactory objDbCommmandFactory;
public TestRepository( IDbCommandFactory DbCommandFactory)
{
objDbCommmandFactory = DbCommandFactory;
}

public void TestMethod()
{
using ( var cmd = objDbCommmandFactory.CreateDbCommandObject())
{
// Code
}
}

Now we are all set to Mock our CustomDbCommand Object, or in other words, our IDispossible object. Happy Unit Testing.

Advertisements