Registering a mock/stub with Windsor

I have some code that uses Castle Windsor to retrieve instances this helps to manage dependencies that I don’t have to worry about, the side effect of this is that when performing unit tests against the code that needs to get an instance from Windsor I want to provide a way to inject a mock/stub object is can be accomplished with the following:

container.Register(Component.For()
                                        .Instance(mockFoo));

To help reduce the amount of code in my test setups I usually have this method in my Unit Testing base class

protected void RegisterDependencyAgainst(TInterface instance)
{
    container.Register(Component.For()
                                .Instance(instance));
}

Which is then called like this:

// in setup method
mockFoo = MockRepository.CreateMock();
RegisterDependencyAgainst(mockFoo);

Staff Intranet on Codeplex

I have not posted here for a little the main reason being I have been putting the final touches to another project I have been working on in my spare time, it’s a staff intranet application what I have tried to do with this project as with the previous projects is try and use it as a learning exercise, so I have incorporated some best practices and design patterns and used them for a real world example, in there you will find:

  • Inversion of control – This has been decoupled from a particular IoC container but I have utilised Castle Windsor under the hood
  • TDD/BDD – Around 98% of the behaviour of the application was designed test first, the reason I have put BDD as well is because I like to think of my tests as defining the behaviour of the application rather than of just testing assertions in my code, this comes out through the naming of my test cases
  • NHibernate – This was my first use of NHibernate and overall I was very pleased with what this very powerful ORM gives you and also keeping the domain clean from database artifacts (persistence ignorance)
  • Model View Presenter – This is the first time I have emplyed model view presenter for web and it acts as a nice interim between moving logic from the codebehind and going the whole hog and using an MVC framework such as monorail or ASP.NET MVC, I’m completely sold on having tests against the UI logic
  • SQL Server 2005 – This was probably the most dissapointing aspect of developing this application, I was hoping that the new client tools would be great and easy to get stuff done with however I found it the opposite things that used to be easy using the SQL server 2000 enterprise manager were not intuituve at all with the Management Studio, examples:
    • Wanting to remove a database that already exists
    • Setting permissions from the users perspective

Anyway after that intro you can find more details over at my project homepage on codeplex.

My hope is that this project will help others who are learning about the above but would like to see them used in a real world context rather than just in hello worls context.

Unit testing threading using rhino mocks

Update: I have recently put together a much more detailed look at this in my obstacles of unit testing series https://journalofasoftwaredev.wordpress.com/2009/05/02/obstacles-of-unit-testing-methods-to-side-step-them-part-2-multi-threading/

I recently had to do some unit testing against my TaskScheduler class this presented a problem… the TaskScheduler performs it’s monitoring by spawning a worker thread in the background so I needed a way to test this asynchronous behaviour. Thanks to the excellent Rhino Mocks and using the ManualResetEvent I come up with the following solution:

[Test]
public void Should_run_scheduled_task_when_datetime_met()
{
	ManualResetEvent evt = new ManualResetEvent(false);
	DateTime runAt = new DateTime(2008, 1, 1, 12, 0, 0);
	ITask mockTask = mocks.DynamicMock();
	ITaskRunner mockTaskRunner = mocks.DynamicMock();

	using (mocks.Record())
	{
		SetupResult.For(mockTask.RunAt()).Return(runAt);

		mockTaskRunner.Run(mockTask);
		LastCall.Constraints(Is.Equal(mockTask));

		LastCall.On(mockTaskRunner).Do(new TaskRunnerRunDelegate(delegate(ITask task)
		{
			evt.Set();
		}));
	}

	using (mocks.Playback())
	{
		ITaskScheduler sut = createSUT(new MockDateTimeSource(runAt.AddSeconds(-2)), mockTaskRunner);
		sut.Schedule(mockTask);
		sut.Start();
   	        evt.WaitOne(4000, false);
	}
}

When a Task that the TaskScheduler is monitoring reaches its scheduled execution date/time the TaskScheduler Hands off to an ITaskRunner in this case it’s a mocked out interface, we can use this to listen out for a call to the Run method, and set the ManualResetEvent thus exiting the WaitOne block. The downside to this approach is establishing what the timeout should be in most cases this will be a few seconds.

Unit testing date & time related objects

I was recently working on a scheduler object that relied on retrieving the current date and time to see if any tasks it had were due for execution, this presented a problem, how do you unit test an object that relies on the current date and time?

We could just make no changes to the object and instead make the unit tests highly dependant on the date and time it is ran on and in some cases it might be ok (although highly impractical and dangerous) however for a scheduler this is not feasible.

What we need can be solved by “introducing another level indirection” paraphrased from David Wheeler’s famous quote. What we can then do is setup an interface that can bring us back a DateTime:

public interface IDateTimeSource
{
 DateTime CurrentDateTime();
}

Now we can implement a real-time version that will be used most of the time:

internal class RealTimeDateTimeSource : IDateTimeSource
{
 public DateTime CurrentDateTime()
 {
 	return DateTime.Now;
 }
}

And also a mock version that in this case we can specify when it should start and it just ticks along representing time:

internal class MockDateTimeSource : IDateTimeSource
{
 DateTime providedDateTime;
 Thread realTimeThread;
 readonly object syncLock = new object();

	private DateTime ProvidedDateTime
 {
 	get
 	{
 		lock (syncLock)
 		{
 			return providedDateTime;
 		}
 	}
 	set
 	{
 		lock (syncLock)
 		{
 			providedDateTime = value;
 		}
 	}
 }

	public MockDateTimeSource(DateTime startAt)
 {
 	providedDateTime = startAt;

		realTimeThread = new Thread(delegate()
 	{
 		while (true)
 		{
 			ProvidedDateTime = ProvidedDateTime.AddSeconds(1);
 			Console.WriteLine(providedDateTime.ToString("hh:mm:ss"));
 			Thread.Sleep(1000);
 		}
 	}
 	);
 	realTimeThread.IsBackground = true;
 	realTimeThread.Start();
 }

	public DateTime CurrentDateTime()
 {
 	return ProvidedDateTime;
 }

}

The locking is to ensure that the write in the background thread and the read in the calling thread take place see http://www.yoda.arachsys.com/csharp/threads/volatility.shtml for more info.Now we need to provide the object with the version to use as it’s date and time source, we can do this numerous ways here is an example using constructor injection:

public Scheduler() : this(new RealTimeDateTimeSource())
{
}

public Scheduler(IDateTimeSource dateTimeSource)
{
 this.dateTimeSource = dateTimeSource;
 Initialize();
}

The parameter-less constructor will be used in most cases however for unit testing we can provide the mock version so that our tests can be decoupled from the date and time they are ran.If you wanted to provide extra security so that when the code goes into production users of the scheduler object can never pass in an IDateTimeSource you could change the constructors and also add a conditional preprocessor directive so that the release build never includes the testing constructor.