Navigate / search

Fluent Mocking

In which our hero shouts “Hold on thar pilgrims” at those who would hate Mocking Frameworks.

Here’s a scenario (for once not a hypothetical scenario, this is a real system I worked on). You’re building a wizard based app. To be more accurate you’re building lots of wizard based apps, so you’ve extracted all the wizardy stuff up into it’s own classes. Your apps can now focus on actual bread and butter functionality. When I say ‘You’ I mean ‘I’ but this is a writing device that sucks you into the narrative. I bet deep down you already care a little bit about how these Wizards turned out.

Two of the objects in your Wizardy Stuff code are a ‘Wizard’ and a ‘WizardStep’. A Wizard obviously contains a number of WizardSteps. You get the idea.

There are quite a few tests that we can write to make sure that navigation works. A Wizard has a current step, Moving Next or Previous should increment or decrement the current step. Moving next on the last step causes the Wizard to finish. It’s all very simple, and what you’d expect from a wizard.

Let’s look at an example of the kind of tests we might have to write, and what it means in terms of mocks and stubs. We have a requirement that says that when the user clicks ‘Move Next’ the current step gets to validate itself and decide whether it will allow the Move Next to happen. If it returns false, the Wizard will refuse to allow the user to move on.

To test a feature like this we can do the following:

  • Create a wizard with one step
  • Use a stub for step1 that returns false when the OKToMoveNext method is called
  • Start the wizard
  • Assert that we’re on the first step
  • Attempt to move next
  • Assert that we’re still on the first step

After the attempt to MoveNext we should still be on step1 (because step1 returns false when asked to validate itself).

We can implement the test in various ways. A key issue is how to implement the stub for step1 that simulates a step failing validation. Here’s one example, using the Moq Framework:

	// Listing 1
        [Test()]
        public void Validation_CanPrevent_MoveNext()
        {
            Mock<IWizardStep> step1 = new Mock<IWizardStep>();
            step1.Setup(s => s.OKToMoveNext()).Returns(false);

            Wizard wizard = new Wizard()
                                    .AddStep(step1.Object)
                                    .Start();

            Assert.AreEqual(step1.Object, wizard.CurrentStep);

            wizard.MoveNext();

            Assert.AreEqual(step1.Object, wizard.CurrentStep);
        }

I don’t like this code. It’s too busy. There’s too much “stuff” that’s related to the mocking framework. The intent of the test might be discernible, but only just. The shaded lines in particular need a second or third glance to make sure you’re reading them right. Our intent is to create a stub wizard step that can’t move next. Our test should be screaming that intent so clearly that it cant be missed by someone reading the code.

I suspect that scenarios like this are one of the reasons why some developers find themselves edging back towards hand-rolled mocks and stubs. The equivalent code using hand-coded classes is much simpler and the intent of the test is clearer:

	// Listing 2
        [Test()]
        public void HM_Validation_CanPrevent_MoveNext()
        {
            IWizardStep step1 = new WizardStepThatIsNotOKToMoveNext();

            Wizard wizard = new Wizard()
                                    .AddStep(step1)
                                    .Start();

            Assert.That(wizard.CurrentStep == step1);

            wizard.MoveNext();

            Assert.That(wizard.CurrentStep == step1);
        }

The shaded code tells most of the story. Because we’re creating a simple class for a specific purpose, we can be very explicit with our naming.

Although listing 2 is an improvement over the code we produced using the Moq mocking framework, it’s not without it’s troubles. Our suite of tests is going to need a lot of different mocked WizardSteps to cover the various scenarios. Many will be very similar, or will have parts that are identical to parts of others. For example, we might have half a dozen version of the class that need to prevent a user Moving Next, but each may need to do that in conjuction with some other different behaviour.

We could try to make our Handmade mocks more intelligent, but that’s a slippery slope. Once you start adding in “one more little tweak, to facilitate one more test”, you quickly find yourself with a mock that’s more complex than the code you’re trying to test.

One interesting option is to go back to using our Mocking Framework, but hide the messiness of it behind a slightly nicer abstraction. Imagine being able to write a test like the one in Listing 3:

	// Listing 3
        [Test()]
        public void step_can_stop_move_next()
        {
            IWizardStep step1 = new MockWizardStep()
                                    .ThatCannot.MoveNext
                                    .Object();

            Wizard wizard = new Wizard()
                                    .AddStep(step1)
                                    .Start();

            Assert.AreEqual(step1, wizard.CurrentStep);

            wizard.MoveNext();

            Assert.AreEqual(step1, wizard.CurrentStep);
        }

This is a fluent style interface, but behind the scenes it’s doing all the same stuff that our first test did. The beauty of a mocking framework is that you can assemble the functionality you desire at runtime, rather than needing to code a specific class for the specific case you want to test. Once you’ve written the Factory that spits out mocks, you can use it to spit out other variations of the MockWizardStep:

	// Listing 4
            IWizardStep step1 = new MockWizardStep()
                                    .ThatCan.MoveNext
                                    .Object();

            IWizardStep step1 = new MockWizardStep()
                                    .ThatCan.MoveNext
                                    .ThatCannot.MovePrevious
                                    .Object();

Once you have the fluent interface in place it gets a lot easier to create exactly the right mock for the scenario you want to test. The test becomes clearer, and to a certain extent you’ve abstracted your tests away from the specific mocking framework that you are using.

It’s not all ribbons and bows. One problem is that you have to actually build the fluent interface. You can’t really make a generic one of these. A fluent interface by it’s nature is a Domain Specific Language. You implement a language based on the properties of the objects you’ll be mocking.

Creating the Fluent Interface isn’t a particularly complicated task (see Listing 5), but it’s enough work that you need to think carefully about whether it will pay for itself. The example here is also artificially simple, showing only a few stub methods. When you get into creating a fluent interface that allows you to configure Mock behaviour, like verifying method calls etc, things could get a little hairy.

It’s worth looking more closely at the shaded code in Listing 5, we what appears to be a readonly property, modifying fields within the class. What madness is this? It’s nothing really, just a trick used in constructing fluent grammars to avoid having parenthesis after every term in a statement.

    // Listing 5
    public class MockWizardStep
    {
        private Mock<IWizardStep> _step;
        private bool _thatCan = true;

        public MockWizardStep()
        {
            _step = new Mock<IWizardStep>();
        }

        public MockWizardStep ThatCan
        {
            get
            {
                _thatCan = true;
                return this;
            }
        }

        public MockWizardStep ThatCannot
        {
            get
            {
                _thatCan = false;
                return this;
            }
        }


        public MockWizardStep MoveNext
        {
            get
            {
                _step.Setup(v => v.OKToMoveNext()).Returns(_thatCan);
                return this;
            }
        }

        public MockWizardStep MovePrevious
        {
            get
            {
                _step.Setup(v => v.OKToMovePrevious()).Returns(_thatCan);
                return this;
            }
        }

        public IWizardStep Object()
        {
            return _step.Object;
        }

        public Mock<IWizardStep> Mock()
        {
            return _step;
        }
    }

So, where does that leave us? Are mocking frameworks saved from those who would hate them? Well, probably not, but for everyone else here’s one more tool in your toolbox for that day when the perfect scenario presents itself.

So Over Mocking Frameworks

In which our hero peddles more of the stuff that wasn’t good enough to make it into his TDD Session, and passes it off as an interesting blog post. Welcome to the blog equivalent of the “extras” section of a DVD.

During the course of preparing and presenting my session on Test Driven Development, I had quite a few interesting conversations with quite a few interesting people. Some were the face to face kind of chats that you inevitably have after presenting a session, some were via email.

One theme that popped up more than once was the notion of being “over” mocking frameworks. And when I say “over” I mean it in the “girlfriend from college that you’d rather not see any more” sense of the word.

It appears that when it comes to mocking, TDD practitioners go through a number of phases.

  • Ignorance – How to I test this object, it has all these dependencies?
  • Interest – Hmmm I can create classes that implement the same interface as a dependency.
  • Excitement – Holy crap, mocking frameworks are da shizzle, I want to use them everywhere.
  • Hmmm – Why is it complicated to do this with a mocking framework. A hand coded class would be so much simpler.
  • Disillusionment – Holy crap, mocking frameworks are a pain, I don’t want to use them anywhere.
  • Righteous Indignation – Dude! You’re using Mocking Frameworks? that’s like so 2009.
  • Perspective – Mocking frameworks, handrolled? Meh! Both have their place

As with virtually everything else in life, extreme views for or against Mocking frameworks are unlikely to be helpful to anyone. They’re a tool. Ignoring them completely (or consciously not using them) is no more helpful than surrendering to them and using them blindly.

In a future post I’ll look at how to mitigate some of the issues that cause people to “get over” Mocking Frameworks. I’ll also look at some of the issues that need to be addressed when using hand rolled mocks and stubs.

Test Driven Development – Pushing Through The Pain

Sample Code
TDD Sample Code for DDD South West

Last weekend I presented a session on Test Driven Development at DDD South West in Bristol. I actually presented the session twice thanks to being voted onto the repeat track, and in total I had 120 brave souls who came along to see the session.

I’ve taken the past week to go back over the sample code that accompanies the session and tidy it up a bit, add some ‘discussion’ comments about various issues, and also factor in a few suggestions that I received on the day.

The code can be downloaded from the link at the top and bottom of this post. The slides can be viewed here:



Thanks to everyone who came along, that especially to everyone who left feedback, and virtually everyone did. This session started with a 90 minute running time, I cut it to 1 hour for DDD South West, but it still felt a little rushed. My hope is to cut it dramatically in time for DDD North (if I’m fortunate enough to be invited) and cover less ground, but in more detail and with more time for interaction and questions from the floor.

If you have any problems with the code, or if you’d like to point out some issues with it then leave a comment or find me on twitter (@richardadalton).

Thanks for stopping by.

Sample Code
TDD Sample Code for DDD South West

Retro Fitting Unit Tests to Legacy Code

This post references a StackOverflow thread which you can read
here

One of the problems with TDD is that those who try it, often begin by booting up NUnit or something similar, writing a few trivial tests to get the lie of the land, then instead of doing TDD (i.e. Writing a test and then writing some code to make the test pass) they do something much much harder, under the mistaken impression that it will actually be a way to ease themselves into TDD.

They do what I did, they start out by trying to write some unit tests for existing code. Either a past project, or more likely the project they are currently working on. They quickly discover that these projects are (from their perspective) virtually impossible to test.

The reason why is obvious, 1) They are new to writing automated tests, which is a tricky enough skill to master, but more importantly 2) They are new to writing testable code which is actually a significantly bigger challenge than writing tests. The chances that their old projects contain testable code is virtually nill.

So, our protagonist is actually starting their journey to TDD with an obstacle that is actually beyond the ability of some seasoned TDD practitioners. Think a video game with the ultimate Boss level as the very first thing you do, before you learn the controls or understand much of anything about the game. That right there is a game that you’ll probably throw in the bin after about an hour, if you last that long.

In my research for my TDD session at #dddsw I found lots of interesting questions, blogs and articles, most of which I didn’t have time to fully discuss during the session, but I’ll point you in the direction of some of them over the next few days/weeks.

The first is a Stack Overflow discussion on how to write automated tests for a complicated function with lots of dependencies.

It’s notable because it’s not an uncommon problem, and the answers cover the usual spectrum from practical solutions to pragmatic advice to questioning the validity of the original question etc.

It’s also notable because Uncle Bob contributes an interesting Step By Step on how to add tests to existing code (in an kludgy way) and then how to refactor both the original code and the kludgy test handling.

Original Thread Here

Enjoy.

DDD South West 3

It’s 11.30, I’ve got work in the morning, I’m knackered and I’m still sitting in front of a computer having just tried out some things that I picked up at DDD South West over the weekend. That’s the effect that participating in the DDD community can do to you. It recharges those tech/geek batteries and for a few hours or a few days programming feels a little like it did when I was 15.

If there’s a downside to being a speaker it’s that the preparation for speaking sucks up a lot of time (at least it does if you need to prepare like I do). So things slide by un-researched or not studied properly. Having spoken at DDD Scotland last month and now DDD South West, with two different sessions, I’ve been heavily focused on DDD for about 4 months, while things I’d like to look at more closely like Threading and Rx for example haven’t gotten the attention they deserve.

The flip-side of this little faustian pact is that when I get to DDD I make up for lost time either in sessions or more often in the informal chats and demos (un-sessions as Paul Stack calls them) that spring up around the conference itself.

As usual on the day I didn’t get to see many of the other sessions. In fact I only saw Colin Mackay’s session on Parrallellization (I, like Colin hope I spelled that right, probably didn’t, but don’t really care.).

My latest project leans heavily on Threading but uses the older syntax. I haven’t had a chance to really look at the new (not so new any more) threading syntax, so this was a session I didn’t want to miss. It didn’t disappoint.

Within a few minutes of flopping into the recliner after the long trip home the laptop was open, and I was trying out some of the stuff Colin had shown us. I’m really blown away. I had touched briefly on the issue of Testing Threaded code in my TDD session and this is an area that I’m going to be spending a lot of time on over the next year or two.

I reworked my sample code using the new syntax and not only did the intent of the code become clearer, I removed all of the locks I was using (probably incorrectly) and at the same time removed an intermittent race condition bug that was in the code.

Apart from Colin’s session the only others that I attended were my own. I was on deck twice thanks to my TDD talk getting voted onto the repeat track. In a quirk of scheduling I presented on the Repeat Track before I presented in my originally scheduled spot.

The repeat track was presented in quite a small room. It got the day off to a nice start to be presenting to a full room, we had to turn a few people away and ask them to come to the main session later in the day.

The main session was in the Track 1 room, which is a pretty big room. That also felt pretty full, which suggests that there’s a real appetite for TDD, which is odd because in many ways things have moved beyond TDD and the focus has switched to BDD and so on. I wonder if the opinion shapers in the industry have perhaps gotten bored of something and moved on just when the mass of developers are only just catching up and really getting interested. I think I might try and stick to my philosophy of speaking about out of date topics and see of there continues to be a market for it.

I did have a slight fear that a TDD session could end in tears (if not mine then someone elses). At an event like DDD there’s a strong chance that the audience will include a significant number of people who fall into one of the following categories.

1. People who know more about TDD than I do, but come along for a look.
2. People who hold diametrically opposed views to mine, regardless of my views.
3. People who haven’t really gotten into TDD but have already been turned off by the hype.

It can be hard to include anything in such a session that will see any of these people come away with anything of use.

I’m sure there were some in the audience who got very little from the session, there always will be and I hope they left feedback so I can include some things for them, but I was delighted to receive some very kind commends from a number of people who I really didn’t expect to have benefited from the session.

Funnily enough I speak at these conferences in the hopes that I’ll energize a few developers to try out things like TDD, and I come away energized myself. Strange how that works.

The un-sessions were as always brilliant. An informal demo of TeamCity by Paul Stack addressed a few issues I’ve been having, and I got to show him my favourite simple trick – the miracle of creating a text file with a UDL extension and then double clicking on the icon.

A few people approached me with questions and suggestions about my session which I’m going to incorporate before I release the slides and code.

At the Geek Dinner on Saturday night I had endless fascinating conversations, from a chat about recruitment with Tim Gaunt who’s responsible for the brilliant http://borninthebarn.co.uk/ to picking Colin Mackay’s brain a little further on threading, to the usual round table moaning about how you can never have enough monitors to the best ways of encouraging community participation and on and on.

Retiring to the pub led to a fantastic chat with Graeme Foster about where technology will be in our kids lifetimes, and their kids lifetimes, to where we’ve come from (ZX81s and the BBC Micro). We talked for hours and never got around to talking about the thing we met up to talk about – Domain Driven Design.

From pub back to hotel and an oddly circle of chairs let to a long discussion on topics as wide ranging as The Rapture and Creationism, 80’s Rock Legends and how to impersonate them, Restaurants with strange bathrooms, Oldest, Youngest and most interesting birthdays, and most famous namesakes, Sci-Fi TV shows, various attempts at Pun inspired humour that resulted in threats of physical violence, all leading to an analysis of the lyrics of the Spitting Image Chicken Song with particular emphasis on the best order in which to accomplish the tasks outlined in said song.

The party broke about after 1am, and I went back to the room pondering the notion of an 8am for a taxi to the airport.

This morning (Sunday) as I slinked down to the lobby with a few minutes to spare before the Taxi arrived, I found a handful of DDD’ers getting through breakfast.

If you are not already part of this Community then sort that out at DDD North in Sunderland on October 8th. If you’re a software developer and you are not participating in some way in the wider development community, you really are missing all the best bits.

Thanks to everyone who grafted to make DDD South West go smoothly. I hope to be back in Bristol this time next year with an even better session.

Aer Lingus vs Ryanair

I’m currently getting ready to present at DDD South West in Bristol on June 11th. In addition to the normal work of creating sample code and slides, I also have to figure out flights and a hotel.

In the past I’ve tried to avoid Ryanair. There was a time when it was actually worth paying a little more to fly with Aer Lingus. That’s no longer the case.

I don’t know if it’s the 25% stake that Ryanair owns, or just an inevitable progression in the airline industry, but I can no longer see any difference between Ryanair and Aer Lingus.

That’s not true. There is one difference. The price. Aer Lingus seems to be embracing everything about the Ryanair business model, except the price.

Let’s look at an example.

I’ve just booked return flights to Bristol with Ryanair, flying from Dublin at 21:15 on the 10th of June, returning at 10:55 on the 12th.

The headline cost of the flights were €3.99 each way. Ryanair add a Web Check-in fee of €6 each way, giving a total of €19.98

On Aer Lingus, the cheapest outward flight is €4.99, but it leaves at 6:25 on Friday morning. Of course that would mean missing a day of work and being at the airport at an ungodly hour. There’s an 18:45 flight for €14.99.

But let’s take that €4.99 flight, it makes the comparison more interesting. That’s €1 more than the Ryanair flight. There’s a €4.99 return flight on Sunday, also at a stupidly early time. How does this extra €2 pan out if we proceed to try and book the flight?

As I mentioned, with Ryanair we add a further €12 euro for a total cost of €19.98. You’d imagine the extra fees would be pretty similar for Aer Lingus right? They are departing from and arriving into the same airports after all.

I was stunned to find that Aer Lingus charge €19.99 EACH WAY in “Taxes and Charges”.

Think about that. The Taxes and Charges EACH WAY on an Air Lingus flight cost more than the entire cost of a round-trip ticket with Ryanair.

What are these Taxes? What are these Charges? Why don’t they apply to passengers flying with Ryanair?

And we haven’t even gotten to the extra fees for credit card booking etc.

One of the things that annoy people most about “Low Fares” airlines and indeed other businesses is the extortionate fees for paying by credit card. The online business model allows companies to radically reduce their overheads, but rather than pass on those savings they charge customers for the “convenience”.

With Ryanair and Aer Lingus the fee for paying by card (as if there were another option) is €6 each way, per ticket. Not per transaction…Per Ticket, Per leg of journey. That’s €12 for a return ticket for one person.

Unlike Aer Lingus, Ryanair usually has at least one type of card which allows you to avoid this charge. Annoyingly they keep changing it. I’m in luck this week, I have a prepaid Master Card that I bought at Christmas, and Ryanair allow it to be used without charging the €12 fee.

With Aer Lingus the fee is also €12, but there doesn’t seem to be any way of avoiding it.

So, to sum up.

Ryanair, Headline Ticket Price €3.99 each way. Final Total €19.98
Aer Lingus, Headline Ticket Price €4.99 each way. Final Total €61.96

Some day, very soon Aer Lingus will cease to exist. I don’t know what it’s final demise will look like, but it will vanish. When that happens there will be much hand wringing and questioning about how such a thing could happen.

The answer is simple and we’ve known it for a long time. Aer Lingus is taking the piss.

The quest for syntax highlighting

I’m having a hell of a time displaying source code in blog posts. I’ve found no end of plugins but all of them seem to have issues. Here’s my latest effort, and it seems to be the best solution so far.

I’m using the “SyntaxHighlighter Evolved” plug-in for WordPress. It handles indents which is a good start, I had a lot of trouble getting any solution that maintained the formatting of code, which let’s face it is kind of the point.

public class Controller
    {
        private int _sampleSize;
        private ICoinFlipObserver _observer;

        public Controller(int sampleSize)
        {
            _sampleSize = sampleSize;
        }

        public void AddObserver(ICoinFlipObserver observer)
        {
            _observer</span> = observer;
        }

        public void RunSimulation()
        {

        }
    }

One nice feature is the ability to show the code collapsed, and let the user click to expand it by clicking on it. The title that shows for the collapsed code can also be configured, handy if your post shows multiple listings. Unfortunately once the user has expanded a listing, they can’t collapse it again, this seems like a bug.

Another nice feature of this plugin is the ability to highlight lines of code as seen above with lines 7-9 and 13-16. It’s achieved with a comma separated list of lines, and it allows ranges. There’s another little bug there, when specifying the lines to highlight, I couldn’t say “7-9,13-16”, I had to say “7,7-9,13-16”. It appears the first item needs to be an individual line, after that it works as normal.

If these are the only issues I encounter I’ll be happy to keep using it.

How to build a framework and why you almost never should.

Sample Code
WizardFX

Above is a link to the Sample Project for the “How to Build a Framework” session that I presented at DDD Scotland. Below are the Slides. There’s a good deal of information from the session that isn’t in either the slides or the code so I’ll be doing a full write up as soon as time permits, which will probably be sometime after DDD South West in June.

As always please remember this code was written to demonstrate certain ideas, it isn’t production quality code, use it if you like, but don’t expect too much from it.

Incidentally some of the accompanying tests will be discussed in my Session on Test Driven Development at DDD South West.



And here’s the feedback I received from the attendees in Glasgow who were kind enough to fill in the feedback forms.


DDDScot "Frameworks" Feedback
DDDScot "Frameworks" Feedback

DDD Scotland 2011

Last weekend I headed to Glasgow to speak at DeveloperDeveloperDeveloper Scotland.  My third DDD, my first as a speaker.

The speaking experience is a little different.  I presented during the last session of the day which meant that for the entire day I was “yet to speak”.  Which meant that I spent a good deal of the day sneaking off into quiet corners to run through the slides, or look at some source code.

I also gave a quick Grok Talk on Fitnesse, although I could have passed on that, I spoke last which meant I was still speaking as people flooded back into the room for the after lunch sessions.  A case of one Grok too many I think, but no harm.

I was pretty happy with how my session went. “How to Build a Framework, and why you almost never should” seemed to go down well, it drew a larger attendance than I had expected, considering the excellent sessions that were on at the same time.

The session feedback was very positive.  One or two people suggested slowing things down and spending more time looking at the sample framework. These are two things I was conscious of going in.  Despite cutting huge chunks of what I’d like to have covered, it was still a push to get everything into the 50 minutes or so available.

In retrospect it would have been better to talk less, demo more and give a good write-up to cover anything I couldn’t get to on the day.   Let’s see if I can put that into practice at DDD South West in Bristol next month.  It’s a completely different session, but one I’m looking forward to…”Pushing through the pain of TDD”.

In the meantime, watch this space for the slides, sample code and write-up of the Frameworks Session from DDD Scotland.