Unit Testing with Dependency Injection
"Unit Testing". It's the buzzword in the I.T. field right now it seems. To clarify, Unit Testing is for automating testing on a small piece of code. I don't know why managers toss around the word like it's an "expected" part of testing as simple as just running the app. Of course, if the app has no UI, that also doesn't make sense. LOL. But, unit testing is a discipline that requires planning and the mindset of having good coverage on all your code which you expect to always function. Wikipedia defines it like this:
unit testing is a software verification and validation method where the programmer gains confidence that individual units of source code are fit for use. A unit is the smallest testable part of an application.
Now, read over that statement again so you fully comprehend the idea beind it.
Now that we know that, I will mention Dependency Injection -- at a high level. Dependency Injection (DI) is the process of creating initialization routines (constructors or creator methods) with an interface that will define internal functionality of a piece of code.
For example, let's say you have a class that grabs a DataSet from a db and manipulates it. You just want to test the manipulation of that data without actually hitting a database. How do you do it? Create an initializer that expects an implementation of a used object.
public class DataManipulatorFactory
{
private IDataAccessor _dataAccess;
public DataManipulatorFactory(IDataAccessor dataAccessImplementation)
{
if (dataAccessImplementation != null)
_dataAccess = dataAccessImplementation;
else
_dataAccess = new DatabaseDataAccessor();
}
}
And now that we have this, we can create a mock of IDataAccessor and create a true unit test that only tests the DataManipulatorFactory without relying on a database for passing functionality.
Thursday, May 07, 2009 3:20:43 PM