New Project with NMock
I’m starting a new project that’s been on my idea-backlog for quite a while now. Since it’s a personal project, I get to play around with some new tools and techniques. The first new thing I’m trying out is NMock.
NMock will let me do true unit testing (according to Scott Ambler’s definition) by removing the connection to anything outside of my application. The big thing I’ll be avoiding is the database. In the current application I’m working on at the office, many of our unit tests depend on the database. We need to really read or write data in order to test our business objects. I’ll be using dependency inversion by passing in a data accessor object to my business obects. For unit tests, I’ll be passing in a mock object and controlling the expected response. For component testing, I’ll pass in the fully functional data accessor object that does connect to the database.
In order to use NMock, you need to use interfaces. These are similar to abstract classes, except they only define the method and property signatures that are required for a class to implement the interface. For example, I want to have a Login() method that my data accessor class uses to take a user name and password, and have it return the GUID of that user (or an empty GUID, if the user name and password are not valid). Here is what the interface file looks like:
namespace Library
{
public interface IDataAccessor
{
Guid Login(string userName, string password);
}
}
From here, I’ll need to pass in an object of type IDataAccessor to any other objects that I want to have call the Login method. With NMock, I can have my unit tests create an object that has the method signature of the interface, but I can also say that when I call Login with a value of “userName” and “userPassword”, I want it to return a specified value. That way, my unit tests won’t require that my database is running or that I’ve pre-populated it with a user that has that user name/password/GUID value. Also, since my unit tests won’t be touching a real database, they’ll run significantly faster. That will make continuous integration easier.
As I build out this code more, I’ll show how it’s implemented.