A Non-Framework Based “Given When Then” Unit Testing Style

2011 November 8
by admin

I was a tad sceptical about the whole BDD thing I first heard about it (I think it was badly sold to me). It took me a while and the help of Anthony Marcarno (amongst others) to see the value of the Scenario based “Given When Then” way of developing acceptance criteria – and hence tests. Initially (where I was working at the time) we derived real value from simply using was of framing stories to escape the trap of thinking purely in terms of our technical tasks when planning stories. The example/scenario based approach was easy for our (non-technical) product owner and main stakeholder to understand and participate in. This alone is justification enough for the so-called Behaviour Driven Development approach – although I always preferred the term “Acceptance Test Driven Development“.

So when I went to the SpecFlow sessions at the Progressive .Net Tutorials in 2010 I was quite attracted to that framework as a means of driving test code generation from Cucumber specifications (feature files) that could (in theory) be written by our stakeholder or a non-technical analyst. Unfortunately this all came towards the end of a long project, so we never really managed to give the SpecFlow approach a thorough rinse.

I’m now fortunate to be working in a development environment at Esendex where TDD is a fundamental aspect of our approach. So, it’s no surprise there are to very smart and TDD experienced people I get to work with who are constantly looking at improving practises in this area.

So, to cut a long story short, a style evolved earlier this year from the team that does not rely anything but Moq and NUnit as external dependencies in our testing code. We explored StoryQ, FitNesse and SpecFlow (amongst others I think). However, since Esendex has a much more developer centred environment (where project execution is concerned). The (direct) stakeholders are often technical anyway, these frameworks were often found to get in the way of good testing code quality. What resulted was a team testing style that allows for a behaviour driven approach – for unit level, integration and end-t0-end acceptance tests. So behaviour required by customers can drive the development of code more clearly.

So here’s an example story & scenario:

Story:

As a website user

I want to be redirected back to the home page when I successfully log in

So I can carry on using the website with member enabled features

So a simple “happy path” scenario would be:

Given a login page

When valid username/password combination is entered

Then the credentials are used to authenticate

And the user is redirected back to the home page

So, if we were to use C# to build an ASP.Net MVC web application and write test code to cover this scenario in our “old” style (using NUnit and Moq) we could come up with the following simple test fixture for this scenario:

using System.Web.Mvc;
using ExampleTDDWebApp.Web.Controllers;
using ExampleTDDWebApp.Web.Models;
using Moq;
using NUnit.Framework;

namespace ExampleTDDWebApp.Tests
{
    [TestFixture]
    public class AuthenticationControllerTests
    {
        [Test]
        public void Login_WithValidUserCredentialsRedirectsUserToHomePage()
        {
            const string username = "bill@ben.com";
            const string password = "flobberdob";

            var mockAuthenticationService = new Mock();

            mockAuthenticationService
                .Setup(service => service.AuthenticateUserCredentials(username, password))
                .Returns(true);

            var authenticationController = new AuthenticationController(mockAuthenticationService.Object);
            var actionResult = (RedirectToRouteResult) authenticationController.Login(username, password);

            Assert.That(actionResult.RouteValues["controller"], Is.EqualTo("Home"));
            Assert.That(actionResult.RouteValues["action"], Is.EqualTo("Index"));

            mockAuthenticationService.VerifyAll();
        }
    }
}

So that’s not too bad – we’ve driven the code design from tests (simplistic as it is), but it doesn’t really reflect the Scenario – at least in terms of the way it reads. If test code is supposed to act as documentation then it isn’t clear what the scenario was that this fixture came out of. Also we’ve got 2 clear assertions in there and one slightly less clear one (in the form of the mock verification). The other thing here is that the arrange/act part of the test is all in the one test method – again, potentially making it less readable.

How about this then:


using System.Web.Mvc;
using ExampleTDDWebApp.Web.Controllers;
using ExampleTDDWebApp.Web.Models;
using Moq;
using NUnit.Framework;

namespace ExampleTDDWebApp.Tests
{
    [TestFixture]
    public class AuthenticationControllerLoginSuccessfulTests
    {
        private const string VALID_USERNAME = "bill@ben.com";
        private const string VALID_PASSWORD = "flobberdob";

        private Mock _mockAuthenticationService;
        private RedirectToRouteResult _actionResult;

        [SetUp]
        public void GivenALoginController_WhenUSerSuppliesValidCredentials()
        {
            _mockAuthenticationService = new Mock();

            _mockAuthenticationService
                .Setup(service => service.AuthenticateUserCredentials(It.IsAny(), It.IsAny()))
                .Returns(true);

            _actionResult = (RedirectToRouteResult)new AuthenticationController(_mockAuthenticationService.Object).Login(VALID_USERNAME, VALID_PASSWORD);
        }

        [Test]
        public void ThenTheAuthenticationServiceIsCalledWithTheCredentials()
        {
            _mockAuthenticationService.Verify(service => service.AuthenticateUserCredentials(VALID_USERNAME, VALID_PASSWORD));
        }

        [Test]
        public void ThenRedirectionGoesToTheHomeController()
        {
            Assert.That(_actionResult.RouteValues["controller"], Is.EqualTo("Home"));
        }

        [Test]
        public void ThenRedirectionGoesToIndexAction()
        {
            Assert.That(_actionResult.RouteValues["action"], Is.EqualTo("Index"));
        }
    }
}

That’s loads better:

  • Tests clearly separated – this case one assertion/verification per test method.
  • Setup and Test methods reflect the scenario – and hence required behaviour
  • Setup (Given and When) is less dense.
  • Verification on the mock Authentication service is more explicit
This style was adopted earlier this year in the development team at Esendex for pretty much all automated tests we write – Unit, Integration and even End-to-End Acceptance tests. It’s become a part of our development culture – so much so that it feels odd when not writing tests using this style.
What next? Well my esteemed colleague @MrAndrew is currently working on a BDD plugin for NUnit – this hopefully should improve things by adding some useful syntactic sugar into the mix when marking up the test code with more obvious ‘Given’ ‘When’ and ‘Then’ type attributes.
Thx to all the @Esendex dev team (current and former) – @samwessell, @darrenliddell, @neilkilbride, @jbjon and @ruby_gem for bringing me round to this!

More Epic Stuff – EV006 – Leeds vs Sheffield

2010 July 28
by admin

Ok so it’s taken a while since it’s initial inception but my partner in crime, @jvictor, and I have finally delivered the awesome Yorkshire soundclash that is “Leeds vs Sheffield”….

Leeds vs Sheffield cover art

It’s part of the ongoing EpicMixTape project, that now has a splendid new blog – and several new releases, including @abeeken‘s superb All Rush Mix Tape and totally Rawk Reading Festival 2002 mix by @gecko84.

This new one by us is an effort to spotlight some of the incredible music that has come out of these two great Northern cities. For my part, I took Leeds – sitting like a giant at the end of the M1 and having a former reputation for utter grim-ness, but in more recent times has become apparently incredibly trendy and affluent. These are, of course, both stereotypes, and I have to admit I’m actually no where near as familiar with Leeds as with Sheffield. So, when it came to music I was surprised how many acts came from there that I completely love – LFO, Age of Chance and Nightmares on Wax, I’d always thought of as Sheffield acts! Then there’s other seminal post-punk acts like Gang of Four – you can see where their influence is on more recent pop acts like Kaiser Chiefs. Of course I knew the mighty Cud band and Wedding Present from my Indie/student days. For lighter pop relief you have the likes of U-u-u-tah Saints and Soft Cell – and on the opposite end of the scale you have the doom-laiden Gothic Punk acts such as Sisters of Mercy and Red Lorry Yellow Lorry. So, quite a bit of variety. There’s also some other notables I had to leave out (due to space/time) – including The Mekons, The Three Johns and Chumbawumba.

Anyway – here’s the track listing:

1 “Damaged Goods” – Gang Of Four
2 “Never Miss A Beat” – Kaiser Chiefs
3 “You Tear The World In Two” – Pale Saints
4 “Hand On Heart (Album Version)” – Red Lorry Yellow Lorry
5 “Alice” – Sisters of Mercy
6 “I Want You” – Utah Saints
7 “Tied Up” – LFO
8 “I’m For Real” – Nightmares On Wax
9 “What?” – Soft Cell
10 “Slack Time” – Cud
11 “Go Out And Get ‘em Boy!” – The Wedding Present
12 “Kiss” – Age Of Chance
13 “Urban Spaceman” – Cud
As with EV003 it is designed to go on a c90 cassette tape.
Next project really will be EPIC – I’m hoping to do a three-parter called “My Electronic Life”… Stand By….

EV003: My Mix Tape Epic

2010 April 12

As someone who grew up in the 80s not having much spare cash but loving music, cassettes and home-taped albums/compilations etc. were a vital way of sharing and discovering music. I would have loved to have bought all the LPs I have now back then, but I just didn’t have the money. The social side was just as important too – whether showing-off, sharing with mates, going to a party of trying to impress prospective girlfriends. I made quite a few and gave quite a few away.

After a recent tidying session in my loft, the re-discovery of a load of cassettes, the acquisition of an actual cassette deck, I got myself into a multi-way twitter coversation with @russelltanner, @sarahlay, @danslee, @jvictor7 (and others) about making/sharing mix tapes. So of course I felt the urge to contribute to what became the “Epic Mix Tape” project.

It’s a compilation of tunes from 1987 to 1992 when I was at university in Cardiff and first started DJing. I was lucky enough to be and “indie” DJ between about 1989 and 1992 – a “golden era” when I had the chance to play a surprisingly diverse range of tunes to some very big crowds. SInce then the Term “indie” has become somewhat meaningless – consigned largely to the “white boys with guitars” mainstream ghetto. I won’t rant about this right now, but back then it essentially meant “Independant” – a state of mind as much as based on the fact that most of the tunes we played out were on independent labels (Rough Trade, Creation, Factory, 4AD etc.). Also the music was full of joy and a surprisingly amount of it could actually be danced to. So I set to with a stack of vinyl and tried to craft a tape based on this period in my DJing/musical life.

And here are the results – 2 sides of roughly 45 minutes, crackles and all:

alt.87-92 Cover Art

It was recorded off vinyl using Audacity on my macbook, tidied up just a little tiny bit and finally recorded back to cassette on a re-used TDK SA90 (one of the best general purposes cassettes going IMHO). The track listing is as follows:

Side 1:

1.”Nothing Can Stop Us” – Saint Etienne
2.”Take 5″ – Northside
3.”Fishes Eyes” – New F.A.D.s

4.”Cab it up!” – The Fall

5.”Only Losers Take the Bus” – Fatima Mansions

6.”You made me realise” – My Bloody Valentine

7.”Big bad baby pig squeal” – Silverfish

8.”Remember what it is that you love” – The Family Cat

9.”Destroy the heart” – The House of Love

10.”Shallow” – Catherine Wheel

11.”Quick as rainbows” – Kitchens of Distinction

12.”Jacket hangs” – The Blue Aeroplanes

Side 2:

1.”All on you (perfume)” – Paris Angels

2.”Mama told me not to come” – The Wolfgang Press

3.”The storm” – World of Twist

4.”Robinson Crusoe” – Cud

5.”Don’t fear the reaper” – The Bridewell Taxis

6.”Dreamtime (Mix)” – The Heart Throbs

7.”Sweetness and light” – Lush

8.”Deus” – The Sugarcubes

9.”Trumpton Riots” – Half Man Half Biscuit

10.”Buffalo” – Stump

11.”Lil’ Devil” – The Cult

12.”Do it quick” – Snuff


And here’s how it looked:

alt.87-92 (EV003) - The insides

You can find out more about the Epic Mix Tape project by following @epicmixtape on twitter too – join in for swaps!

I’m Back

2010 April 11
by admin

After just under 3 years – I’m back.

Due to time, becoming a Father, spending more time on Twitter etc. V2 of my blog became obsolete. I’ve rebuilt/re-modeled etc. now. I can’t promise to be prolific, but there’s a few things going on now where blog posts would be better that fragmented tweets.

I’ve only re-imported my old posts for posterity and may well have a clear-out soon anyway (some of them seem rather quaint/irrelevant anyway).

Standby for more soon…

Goodbye Ambergate Village Shop/Post Office… Hello Belper Tescoland?

2007 April 16
by Dexter M

When I started blogging a year and a bit ago, I really wanted to stay positive as much as I could. I made a resolution that I wouldn’t just rant all the time – I think I’ve stuck to that on the whole. And, one of the reasons I’ve not posted for nearly 3 months now, is that shortly after my last post I discovered something I had feared, but not heard about – that Tesco had plans to build a massive store in Belper on the site of the old Thorntons factory on Derwent Street.

I was pretty stunned.

After all of the great things going on there over the last few years since I’ve lived up here, this seems like such a massive backward step. I’ve seen :

  • the rise of the Farmers Market
  • the opening and great success of Fresh Basil (delicatessen)
  • flourishing local shops on Kings Street (Howarths, Fresh and Fruity etc.)
  • and of course the re-openning and run-away sucess of the Ritz Cinema

There’s even a “Belper Food Festival” on 15th July this year!

I decided to resist the urge to whinge and moan about the potential corporate bulldozing of Belper on this blog. After looking into it I just became more depressed – it seems the whole area where the development would cover already has “mixed used” designated in the Amber Valley Borough Local Plan – meaning, basically the principal for this kind of development has been established there. Also, it seems, this development has been mooted for quite a few years. Tesco seem to be playing a very long game (longer then any politician can) and have worked out a number of sweeteners – new relief road (bypassing Bridge Street), new library and other “facilities”. I seems like these “facilities” draw people away from the current shopping area (from Bridge Street up King Street to the market square) towards, er, Tesco.

The questions I have are :

  • Does Belper need another (even bigger) supermarket? – it already has 3 (Somerfield, Co-op and Morrisons)
  • Does Belper really need a relief road taking trafiic (and attention) away from the current centre? Is it really that bad?
  • What would we gain by placing a massive 24 hour, 80000sq.ft., 500 car park spaced supermarket right in the middle of the Derwent Valley Mills World Heritage Site? Doesn’t it go against the emphasis of conservation?
  • With the renaissance of Belper, largely through the efforts of it’s own independent business people and cultural pioneers, how will surrendering to the giant that is Tesco help the grass roots development of the town that is going on?

I’ll be going along to Belper Civic Forum AGM on Thurday 19th April at Belper School, to see what their attitude to all this is. And see if any difference can be made.

Which kind of brings me on to what woke me up again and made me so sad/depressed/angry…

On the way back from work today, I noticed our local shop/post office in Ambergate had closed. When I went back along later, a notice outside declared the the shop had closed due to “Early Retirement (i.e. Didn’t want to get up early any more)”.

I was, once again, a bit stunned.

I can’t, with had on heart, say we used the shop all the time, but did regularly go in the for papers, milk, booze and other bits and pieces – just the sort of thing you want a local “corner shop” for. I can understand their desire to retire – good luck to them. However it seems like another sign that I may be clinging on to an old fashioned notion that valuing the the independent and local is good.

I’ll keep clinging and fighting as best I can.

More to follow soon – be warned!

Excessive Packaging Madness # 1

2007 January 20
by Dexter M

We needed some Lemongrass – so we had a go at getting some from our regular fruit and veg shop in Belper – the wonderfully named “Fresh and Fruity”. They’re normally very good, and can supply you with all manner of more unusual herbs and veg. Unfortunately, on this occassion they couldn’t oblige. So, in the end we were forced to resort to going to Sainsburys. Up until that point we’d got all of the rest our shopping from the smaller shops and the Co-op in Belper.

When we found the item in question, the charge for this relatively simple item was 75p for two meagre and slightly cruddy looking three-quarter length sticks presented in the most ridiculously excessive packaging like so…

This seemed bad enough, but we soon released that, apart from being entirely un-required (lemongrass is one of the least delicate of herbs) it also turned out to be entirely non-recyclable!

Also, the fact that these meagre shreds of herbiness had been shipped (probably by air) all the way from South Africa, and, as a result of the sealed packaging were actually going mildewey.

Nice one Sainsburys! Is this you contribution to improving our environment and providing us with good quality value for money products? I’ll buy a bunch for 99p from the market in Derby next time I see one and freeze it – last time I saw one like that, the packaging consisted of a single piece of string!

Vive La Royaume-Uni (part deux)

2007 January 19
by Dexter M

More fun from b3ta

Salut!

Train "Fun"

2007 January 18
by Dexter M

It’s an understatement to say it is a bit windy today. So, of course there are likely to be disruptions on the railways. So I’ve just checked on the Central Trains site and got the following screen…

Helpful huh!

Vive La Royaume-Uni

2007 January 15
by Dexter M


I personally like France a lot – a potentially controversial statement to make for a lot of British (especially amongst some of my workmates). I guess this may be something to do with my Dad’s keen interest in Citroen cars – we had a totally bizarre Citroen DS Safari in the late 70s. Or maybe it’s because I like their approach to food, public transport, public services, culture etc.

However, even I was surprised to hear that at one point in the late 50s a “serious” proposal was made by the French prime-minister Guy Mollet that France and Great Britain merge. Most people have scoffed at this, but in a sense, a more subtle merger is occuring with the EU, the number of Brits buying houses in France (about 500k?) and the number of French coming to work here. This is clearly viewed by most as a positive thing, but the thought of either us would give up our head of state or compromise on our great national instutions seems unlikely given the number of Xenophobes in bothe countries.

Of course there’s already been plenty of comentry on it – including a post by Cyberleader Daz and a very amusing, amiable and positive discussion on Channel 4 News between Jon Snow (and his top quality ties), Raymond Blanc and P.Y.Gerbeau. Blanc was very positive about our food – and rightly so! British food has, potentially, an awful lot to offer. Our pop music (as they both agreed) is somewhat superior to the French version. But maybe we could learn something from them about pulling off “Grand Projects” more sucessfully (e.g. Wembley Stadium and Olympics).

Lets face it, France and the U.K. are like siblings – there will always be a strong bond and respect, even if we squabble from time to time and are envious of each others attributes. Maybe that’s what makes the relationship so rewarding.

The Winter Sun at Calke

2007 January 14
by Dexter M

.flickr-photo { border: solid 2px #000000; }.flickr-yourcomment { }.flickr-frame { text-align: left; padding: 3px; }.flickr-caption { font-size: 0.8em; margin-top: 0px; }


DSCF5129, originally uploaded by dexter_mixwith.

Had a very pleasant walk in the un-seasonally sunny and mild weather at Calke Abbey today with Jayne, Matt, Daisy, Freddy and Kathy. While wandering I took a whole load of pictures – go see them on Flickr if you’re interested.