Monday, April 13, 2009

Rolling your own Mock Objects

One of the problems I have with doing unit testing is the mock objects. the principal is simple enough, I create an object that implements the interface I'm trying to mock, the only problem is I end up creating a least 2+ mocks for every class I'm trying to test. I could use something like Rino mocks but there may be some company policy against using open source, or you just don't want to keep it as simple as passable.

Talking to another developer about this he pointed all I needed to do was to give my mock objects some state to handle what passes or fails; BRILLIANT!! why didn't I think of that. So I took the base class

I added 2 collections:
  1. A Collection of string to handle messages added by the various mocked methods to tell the unit test what has occurred
  2. A second collection of strings to to tell the mock to fail and on what methods based on messages passed to the mock object
public class BaseTestRequest
{
public Collection Messages { get; set; }
public Collection FailOn { get; set; }
private string _currentMessage = string.Empty;

public string CurrentMessage
{
get { return _currentMessage; }
set
{
_currentMessage = value;
Messages.Add(value);
}
}

public BaseTestRequest()
{
Messages = new Collection();
FailOn = new Collection();
}

public bool WasSuccessful()
{
return (!FailOn.Contains(_currentMessage));
}
}
Then I can mock an object like this
public class TestAuthenticationRequests : BaseTestRequest, IAuthenticationRequests
{
public bool AuthenticateUser(string userName, string password)
{
CurrentMessage ="AuthenticateUser";
return WasSuccessful();
}
}

to see the full code with comments check out this Sample Code from the sample project.

No comments: