Injecting Rhino Mocks with Ninject

January 20th, 2010

So today I hit a hat trick. I needed to test a class that had an injected dependency, and needed some functionality that I didn’t want to add to a fake and would rather isolate to the test. I needed to use a mocking framework. This is my first time using mocks (and only my second week of dependency injection) so this may not use best practices, but this _is_ a blog after all.

I’m using Ninject 2 for dependency injection, NUnit 2.5.3 for unit testing, and Rhino Mocks 3.6 for mocking. NUnit has a mocking framework built in but it doesn’t use strong typing, which I think was causing problems with Ninject.

What I’m really showing here is an example of how to inject a dynamically declared mock instead of a concrete fake. The fact that it is in the context of a test is actually irrelevant, but using mocks and fakes are obviously important in testing to reduce the complexity of the test.

Initially I’m using the default ConcreteFoo implementation of IFoo in the test. This test fails as intended:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Ninject;
using NUnit.Framework;
using Rhino.Mocks;

namespace Trifecta
{
    public interface IFoo
    {
        string Name { get; }
    }
    public class ConcreteFoo : IFoo
    {
        public string Name { get { return "You don't want to see me"; } }
    }

    public class FooConsumer
    {
        [Inject] public IFoo Foo { get; set; }

        public FooConsumer() {}
    }

    [TestFixture]
    public class FooConsumerTestFixture
    {
        IKernel Kernel { get; set; }

        [SetUp]
        public void SetUp()
        {
            // This is the standard setup that will need to be overridden in the
            // test.
            Kernel = new StandardKernel();
            Kernel.Bind<IFoo>().To<ConcreteFoo>();
        }

        [Test]
        public void FooConsumerGetsTheFoo()
        {
            // This test depends on a specific behaviour in IFoo, but ConcreteFoo
            // is going disappoint right now.
            var fooConsumer = Kernel.Get<FooConsumer>();

            Assert.That(fooConsumer.Foo.Name, Is.EqualTo("The foo for you"));
        }
    }
}

Settting up and binding the mock is all done in the test method. The mock IFoo instance is created, and the functionality that the test requires is added. IFoo is then bound to a delegate which returns the mock instance. The binding has a condition that causes the mock binding to be used rather than the ConcreteFoo binding, this seems to be easier then setting up the kernel from scratch for the test (possibly I’m just missing how to rebind).

[Test]
public void FooConsumerGetsTheFoo()
{
		// Create a mock implementation of IFoo that has the behaviour the test requires
		var mocks = new MockRepository();
		var mockFoo = mocks.StrictMock<IFoo>();
		Expect.Call(mockFoo.Name).Return("The foo for you");
		mocks.ReplayAll();

		// Bind the mock when injecting IFoo into FooConsumer. This overrides the binding
		// created in SetUp()
		Kernel.Bind<IFoo>().ToMethod(context => mockFoo).WhenInjectedInto<FooConsumer>();

		// fooConsumer's Foo should now be the mock IFoo created above
		var fooConsumer = Kernel.Get<FooConsumer>();

		Assert.That(fooConsumer.Foo.Name, Is.EqualTo("The foo for you"));
}

The test should now pass.

Cliche – an extremely simple view template engine for jQuery

December 21st, 2009

I’ve written a very simple plugin for jQuery that takes a template and a model and returns a view of the model. To make sure it worked I wrote some tests and examples, and since I did that I figured I would write a little mini-site. The plugin itself is pretty straightforward:

(function($){
	$.fn.cliche = function(model){
		var template = $(this).html();
		template = template.replace(/%7C/g, '|');	// pipes in a href like <a href="|... get converted to %7C, convert it back
		template = template.replace(/\|.*?\|/g, function(f) {
			var val = model;
			var fieldParts = f.replace(/\|/g, '').split('.');
			for (var i = 0; i < fieldParts.length; i ++) {
				val = val[fieldParts[i]];
			}
			return val;
		});
		return template;
	};
}(jQuery));

It is used by setting up a template (putting it into a script type="text/html" block is convenient and hides it from display) and calling cliche(model) on the jQuery object:

<div id="output">
	<ul></ul>
</div>
<script type="text/html" id="testTemplate">
	<li id="item|id|"><a href="viewItem?id=|id|">|name|</a></li>
</script>
<script type="text/javascript">
	$('#output ul').append(
		$('#testTemplate').cliche({
			id: 1, name: 'Lorem'
		})
	);
</script>

Cliche is licensed under a Creative Commons Attribution 2.5 Australia license. Check it out at http://cliche.belfryimages.com.au.

RegEx Sandbox

December 15th, 2009

I’ve just made a new tool live, it is a sandbox for playing with simple regular expressions in Javascript. I’ve used a couple of other web-based regex tools, what makes this one different is the result of the regular expression is shown live (as well as a couple of examples of what the regex should look like in code). Try out the RegEx Sandbox at regex.belfryimages.com.au.

Form validation with jQuery

December 9th, 2009

Every time I’ve implemented client-side form validation I’ve started from scratch and done it a little differently. Usually it devolves into a messy set of if statements and duplicated code. Here’s my latest method, which separates the validation rules from the processing. It uses jQuery because if you’re not using a Javascript library you should be. This will only handle relatively simple validation cases.

So start with a form:

	<form id="mailingListSubscription" action="subscribe.php">
		Name: <input type="text" name="name" id="name" /><br />
		Email: <input type="text" name="email" id="email" /><br />
		Phone: <input type="text" name="phone" id="phone" /><br />
		<button type="submit">Subscribe</button>
	</form>

All fields are required, and I’m going to use some magical regex (found on the interthingy somewhere) to validate the email address. This script sets up the rules:

	var rules = [
		{ id: 'name', test: function(val) { return val != ''; }, msg: 'Please enter your name' },
		{ id: 'email', test: function(val) { return val.search(/^[^@]+@[^@]+.[a-z]{2,}$/i) != -1; }, msg: 'Please enter a valid email address' },
		{ id: 'phone', test: function(val) { return val != ''; }, msg: 'Please enter your phone number' }
	];

Each rule has the id of the form element being tested, a message that gets displayed on failing the rule, and a function that validates the value of the form element. I also could add multiple rules for the one input.

This script sets up the submit handler for the form, which does the validation using the array of rules set up above:

	$(function(){
		$('form#mailingListSubscription').submit(function(){
			for (var i = 0; i < rules.length; i ++) {
				var rule = rules[i];
				var target = $('#'+rule.id);
				if (!rule.test(target.val())) {
					alert(rule.msg);
					target.focus();
					return false;
				}
			}
			return true;
		});
	});

On a test failing, the rule’s msg value is shown and the target of the test gets focus. This could be changed to something more user friendly like showing the message next to the target field.

Deleting items in a table with AJAX via JQuery

November 29th, 2009

This is a very straight-forward tutorial on implementing a jQuery-driven ‘delete via AJAX’ feature. Say we have a plain HTML table containing a list of items and a ‘Remove’ link. I’m not going to describe the back-end, but I’m assuming something groovy like CakePHP or ASP.NET MVC. I’ve also assumed that the delete request always succeeds and never returns an error, which may not be the case. The script itself is a more than required but is my preferred method as I can extend the elements in the UI fairly easily.

	<table>
		<tr><td>Chickpeas</td>      <td><a href="/items/delete/1" class="delete">Delete</a></td></tr>
		<tr><td>Garlic</td>         <td><a href="/items/delete/2" class="delete">Delete</a></td></tr>
		<tr><td>Olive oil</td>      <td><a href="/items/delete/3" class="delete">Delete</a></td></tr>
		<tr><td>Tahini</td>         <td><a href="/items/delete/4" class="delete">Delete</a></td></tr>
		<tr><td>Cumin</td>          <td><a href="/items/delete/5" class="delete">Delete</a></td></tr>
		<tr><td>Lemon juice</td>    <td><a href="/items/delete/6" class="delete">Delete</a></td></tr>
	</table>

The delete hrefs (/items/delete/XX) link to an action or page that deletes the specified item and returns a HTTP status of 200 (OK). If the action just redirected to the current page then this table should work as it stands, which is probably a good way to check that everthing works as expected without involving AJAX features. If you just want to set up the client side without implementing any server-side code, create the following in delete_test.php and use it for the delete links:

<?php header('HTTP/1.1 200 OK'); ?>

Make sure that jQuery 1.3+ has been included in the page and add the following:

<script type="text/javascript">
$(function(){
	var ui = {
		init: function(){
			$('a.delete').live('click', ui.delete_click);
		},

		delete_click: function(){
			link = this;
			$.get(link.href, function(data, status) {
				$(link).parents('tr').remove();
			});
			return false;
		}
	};

	ui.init();
});
</script>

Very basic stuff but it works. It could be jazzed up by fading out the items first or updating a status label. If there is a significant delay between calling the delete action and getting a response the user may not think anything has happened, so perhaps the delete link should change or be disabled.

Declaring a class with inheritance and a generic type constraint in C#

November 13th, 2009

I’m writing a generic class that inherits from a base class, implements an interface, and has a type constraint on the generic class. The class inheritance and interface are straightforward, as is the type constraint, but combined together it’s not obvious how to write this. Any examples of type constraints I could find don’t have inheritance or interfaces as well. So, via a bit of trail and error, here is a right way to declare such a class:

public class MyClass<T> :
    BaseClass<T>, IMyInterface
    where T : ClassOfT
{...}

New tool list

November 7th, 2009

I’ve added my tool list to the sidebar. This is a collection of free tools and software that I absolutely have to have on all my computers (there’s a few of them).

jQuery Blink plugin

October 8th, 2009

I love this Blink plugin by John Boker. Not because it’s something that should ever be used (I don’t think that was the intent). It’s just a good, simple reference plugin.

Subversion on a USB stick

September 27th, 2009

I use Subversion for version control at work, so I wanted to use it for a couple of websites and projects that I play with at home. I’ve been thinking about buying a cheap server or NAS that I could set up but couldn’t justify the cost and electricity just for want of version control.

As it happens, my Subversion client of choice TortoiseSVN can create and access local Subversion repositories. Probably all SVN clients can do this, and this is just a feature of the system, but when I’m used to seeing the version control purely as a client/server configuration this was a bit of a surprise. TortoiseSVN integrates nicely with Windows Explorer which makes it extremely easy to work with. If I had to load a seperate SVN client just to commit changes I would most likely put it off and/or forget about it. TortoiseSVN makes working with Subversion so easy that it is the main reason I keep giving up on Linux for my development machines.

One of the attractions of version control is that the project is portable – I can check out (make a local copy of) a website on my home PC, make changes, commit the changes to the server, then update the site on my laptop, without having to worry about copying files (and having different versions of files in the one place). That requires the Subversion server to be accessible on both machines, and if I don’t happen to have internet access for any reason that may not be possible.

Setting up a repository on a USB stick gives me most of the benefits of the typical client/server setup. The biggest downside is a lack of backups, which is something that needs to be maintained on a server anyway, and should be worked around by making backups of the repositories on the USB stick. In any case even if the repository fails I still should have multiple working copies on various machines. Not ideal but at least the files won’t be lost.

So how to do this? First install TortoiseSVN. I’m going to assume familiarity with SVN, and with TortoiseSVN in particular.

On the USB stick, make a folder to store the repositories. I called my folder svnrepos. Inside that folder, make another folder for the first repository. This is the name of the repository so call it something sexy, like bentest. Right click the folder, go to TortoiseSVN, and Create repository here. Wheels will turn, and a message should appear saying the repository was created.

Now go to your development folder, or wherever you want to check out a working copy of the project. Right-click the development folder (eg C:\Development\www) and select SVN Checkout.

The URL of repository is the path to the local repository that you created, as a file URL. Mine is file:///E:/svnrepos/bentest (note there are three slashes after the file: part). The checkout directory is where the working copy will be created. It should be automatically filled in when editing the repository URL, but can be changed. Mine is C:\Development\www\bentest. Click OK and you should have revision 0 of the repository ready to create trunk, branch and tag folders and add content.

Version control. Distributed backups of your precious work. No reliance on internet access and access to private Subversion server. Beautiful.

I haven’t experimented with this so far but I suspect there may be issues if the USB drive comes up on another driver letter. The repository url will probably need to be changed in the working copy. That should be possible via the Relocate command in TortoiseSVN’s context menu.

UPDATE: Relocate is indeed the command to use. TortoiseSVN throws up a warning about corrupting your working copy, but as long as the path entered is the new path to the same place in the repository (eg from file:///H:/svnrepos/bentest/trunk to file:///F:/svnrepos/bentest/trunk) this is the best/only method.

Moving das blog to a subdomain

August 3rd, 2009

OK so I’ve recently moved my blog to a subdomain and noticed that this broke all of the Google search results that I’ve got (dude it’s like 3 hits a month!). No really, search for subversion comments (in Australian pages only) and I’m the sixth result. So to set up the subdomain on my shared host I just used cPanel. That part worked fine, but it meant that all requests to http://www.belfryimages.com.au/2008/03/18/editing-past-log-comments-in-subversion/ got redirected to http://blog.belfryimages.com.au. This was due to the generic .htaccess file that was generated.

To get the old links working I had to rewrite the .htaccess file. This lives where the blog used to be (at belfryimages.com.au/.htaccess):

RewriteEngine on
RewriteCond %{HTTP_HOST} ^belfryimages.com.au$ [OR]
RewriteCond %{HTTP_HOST} ^www.belfryimages.com.au$
RewriteRule ^(.*)$ http://blog.belfryimages.com.au/$1 [R=301,L]

The joy is made in the last line. The ^(.*)$ part is a simple regex that just copies the entire request part, and the $1 in the http… part copies the request into the address of the new redirect.

– fixed the google assert ;-)