Archive for 2013

Recently I’ve become quite interested in the London School of TDD. I blogged before about my experiences doing Luca Minudel’s exercises, in my post “SOLID Principles and TDD“. Since I wrote that, I’ve read Steve Freeman and Nat Pryce’s book “Growing Object Oriented Software, Guided by Tests” and practiced doing some code katas in this style. In my experience there is a lot of confusion around how to use Mocks, and I found it enlightening to see  how the people who invented the technique actually use them.

My current thinking is that there are at least these two areas where London School TDD differs from Classic TDD:

  • Outside-In development with Double-Loop TDD
  • “Tell, Don’t Ask” Object Oriented Design

London School practitioners use Mock Objects as a tool for achieving both. Let’s look a little more about what Mocks are for.

Verifying behaviour

A test case often has three parts: “Arrange – Act – Assert”. In the second edition of his book The Art of Unit Testing, Roy Osherove points out that in the “Assert” part of a test there are three ways to ensure the class you’re testing is behaving correctly. After “Arrange” and “Act”, you can:

  • Check the return value, or an exception.
  • Check the state of the object, or the state of a collaborator.
  • Check the object correctly interacts with a collaborator.

This last form of assertion is generally done using a Mock Object. With an ordinary Mock you set it up in advance to check for a particular interaction, with a Spy, you check after the fact. In either case, you’re asserting an interaction happens correctly. You’re checking a particular object received a particular method call, and you can be more or less strict about the precise details of arguments and numbers of invocations.

In Classic TDD, whenever possible you check a return value or exception. If you’re testing a void method, then you usually take the second option and check state. Only if the other options are really unattractive do you ever turn to using a mock. It’s the last choice.

With London School TDD, the option of using a mock is chosen much more often. You’ll still check return values or object states where that makes sense, but using a mock is often an attractive option. This is because using a mock helps you to both develop your system Outside-In, and to design your objects in an “Tell, Don’t Ask” manner.

Mocks used badly

I think one reason that using a mock object is often the last choice in classic TDD, is because it’s so easy to get into trouble when using them. You should be using mocks to help you improve your design, but all too often the design is bad, and the mocks are either hiding that, or getting in the way.  I sometimes see tests with an enormous “Arrange” part, specifying half a dozen different mocks before they’ve even started calling any functionality. Such a test is bound to be brittle, and could hinder your refactoring to a better design.

The article “Eliminate most Mocks from Unit Tests” by Arlo Belshee gives an example of using a mock to compensate for bad design, and he has several other articles in the series. I think Arlo is largely criticising poor use of mocks actually, rather than London School TDD itself.

It seems to me that you can abuse any technique, and Object Oriented Design is actually very difficult. Steve Freeman has said “No tool nor technique can survive inadequately trained developers“. London School TDD is a design technique that is not easy to master. I talk more about this in my next posts “Outside-In Development with Double Loop TDD“, and “Tell, Don’t Ask” Object Oriented Design.

I’ve been working on this Kata “Gilded Rose” at a few different coding dojos lately. There is even a video of a session I did at the “Tampere Goes Agile” conference recently. In the video, you can see me talking about my Principles of Agile Test Automation, which I have just written about, and updated in my last blog post.

I think these test automation principles are useful to think about when you’re doing the Gilded Rose kata. The basic plot of the Kata is that you’ve just been hired to look after an existing system, and the customer wants a new feature. Having a look at the code, you can see you’re going to want to refactor it a little before adding the new feature, and before you do that, you’re going to want some automated tests.

So the first part of the Kata is to add automated tests to the existing code. You’ve got a requirements document the customer has given you, and you can use it to identify test cases. You’ve also got the code which you can read and execute and work out what it does. The customer is happily using the code in production right now, so you can assume that the behaviour it has is the behaviour they want to keep, whatever it says in the requirements document. (hint!)

Warning – spoilers lie ahead! You should probably try the Gilded Rose kata for yourself before reading on!

When I’ve done this exercise with various groups, I’ve spent a lot of time discussing with people how to make their test cases really readable, and express the requirements clearly, and at the same time useful as regression protection when refactoring the code later.

When you design a test suite you have two main aims – to help you understand what the code should do, (and what it does now), and protection from regression failures when you update it. It can be a bit tricky to do both with the same test suite. If you focus solely on describing the requirements in an executable way, you tend to miss edge cases and there are gaps in the regression protection. If you focus only on regression protection, you’ll spend time analysing the edge cases, and measuring code coverage to see how well you’re doing, but the test cases can become quite hard to read and understand.

You can see for yourself by comparing this test case by Bobby Johnson with this text-based approval test. (It was written by several people at a GothPy meeting). Bobby’s test case is extremely readable and expresses the requirements clearly. He’s done pretty well on the edge cases, but I think he’s missing one or two*. With the text-based approval tests, it’s not so easy to understand what the underlying business rules are, although the regression protection is very good.

When I do this kata with a group, we spend some time discussing the various test cases we’ve come up with, and showing them on the projector. When we did this last week at the Booster Conference, people commented that showing these different test cases had given them a better understanding of “readability” and “regression protection”, and many went on to improve their test suites.

Once you’re reasonably happy with your test suite, the next task is to do the refactoring and add the new feature. How useful are your test cases for regression protection? It’s very easy to make refactoring mistakes in this kata, and you will be testing your tests! You may discover while refactoring that there are more test cases that you want to add. Version control can be pretty useful, so you can run the new test cases against the original code.

There’s also an interesting restriction on your refactoring options – the “Item” class is owned by a nasty-sounding goblin and he doesn’t want you to change his code, so if you do, you have to be prepared for some serious consequences! When comparing refactored solutions at the end of the dojo, this is often an interesting discussion point – did you change the Item class? Is your new design so great that you’re prepared to argue with the goblin for it?!

I havn’t tried this, but I would actually like to try running the text-based approval test against all the refactored solutions at the end of the coding dojo, as input to the retrospective. I think this test covers all the edge cases very well, and would reveal any refactoring mistakes that were not caught by the tests people had developed themselves. That would be interesting feedback to have!

If you havn’t tried the Gilded Rose kata yourself, I do recommend it for practicing writing good test cases. I’d be happy to get a pull request from you if you want to translate the exercise into your favourite programming language, or you can do it in the original C#, as Bobby suggests.

If you’re interested in taking part in a coding dojo with me, I’ll be at several conferences later this year: ACCU in Bristol, XP2013 in Vienna and Test Automation Day in the Netherlands.

* I believe he’s missing a check that the quality of backstage passes doesn’t increase past 50

I’ve previously written about Agile test automation principles, and since then I’ve had some interesting discussions with people that have led me to revise them in this article. In particular, Seb Rose wrote about his 6 principles of unit testing and pointed out some issues with mine. So this article is an update on the previous one, and I’m hoping this will spark further interesting discussions!

I feel like I’ve spent most of my career learning how to write good automated tests in an agile environment. When I downloaded JUnit in the year 2000 it didn’t take long before I was hooked – unit tests for everything in sight. That gratifying green bar is near-instant feedback that everthing is as expected, my code does what I intended, and I can continue developing from a firm foundation.

Later, starting in about 2002, I began writing larger granularity tests, for whole subsystems; functional tests if you like. The feedback that my code does what I intended, and that it has working functionality has given me confidence time and again to release updated versions to end-users.

I was not the first to discover that developers design automated functional tests for two main purposes. Initially we design them to help clarify our understanding of what to build. In fact, at that point they’re not really tests, we usually call them scenarios, or examples. Later, the main purpose of the tests becomes to detect regression errors, although we continue use them to document what the system does.

When you’re designing a functional test suite, you’re trying to support both aims, and sometimes you have to make tradeoffs between them. You’re also trying to keep the cost of writing and maintaining the tests as low as possible, and as with most software, it’s the maintenance cost that dominates. Over the years I’ve begun to think in terms of four principles that help me to design functional test suites that make good tradeoffs and identify when a particular test case is fit for purpose.

Book-128Readability

When you look at the test case, you can read it through and understand what the test is for. You can see what the expected behaviour is, and what aspects of it are covered by the test. When the test fails, you can quickly see what is broken.

If your test case is not readable, it will not be useful, neither for understanding what the system does, or identifying regression errors. When it fails you will have to dig though other sources outside of the test case to find out what is wrong. Quite likely you will not understand what is wrong and you will rewrite the test to check for something else, or simply delete it.

internet_128Robustness

When a test fails, it means there is a regression error, (functionality is broken), or the system has changed and the tests no longer document the correct behaviour. You need to take action to correct the system or update the test, and this is as it should be. If however, the test has failed for no good reason, you have a problem: a fragile test.

There are many causes of fragile tests. For example tests that are not isolated from one another, duplication between test cases, and dependencies on random or threaded code. If you run a test by itself and it passes, but fails in a suite together with other tests, then you have an isolation problem. If you have one broken feature and it causes a large number of test failures, you have duplication between test cases. If you have a test that fails in one test run, then passes in the next when nothing changed, you have a flickering test.

If your tests often fail for no good reason, you will start to ignore them. Quite likely there will be real failures hiding amongst all the false ones, and the danger is you will not see them.

Speed-128Speed

As an agile developer you run your test suite frequently. Both (a) every time you build the system, (b) before you check in changes, and (c) after check-in in an automated Continuous Integration environment. I recommend time limits of 2 minutes for (a), 10 minutes for (b), and 60 minutes for (c). This fast feedback gives you the best chance of actually being willing to run the tests, and to find defects when they’re cheapest to fix, soon after insertion.

If your test suite is slow, it will not be used. When you’re feeling stressed, you’ll skip running them, and problem code will enter the system. In the worst case the test suite will never become green. You’ll fix the one or two problems in a given run and kick off a new test run, but in the meantime you’ll continue developing and making other changes. The diagnose-and-fix loop gets longer and the tests become less likely to ever all pass at the same time. This can become pretty demoralizing.

updatability.001Updatability

When the needs of the users change, and the system is updated, your tests also need to be updated in tandem. It should be straightforward to identify which tests are affected by a given change, and quick to update them all.

If your tests are not easy to update, they will likely get left behind as the system moves on. Faced with a small change that causes thousands of failures and hours of work to update them all, you’ll likely delete most of the tests.

Following these four principles implies Maintainability

Taken all together, I think how well your tests adhere to these principles will determine how maintainable they are, or in other words, how much they will cost. That cost needs to be in proportion to the benefits you get: helping you understand what the system does, and regression protection.

As your test suite grows, it becomes ever more challenging to adhere to all the principles. Readability suffers when there are so many test cases you can’t see the forest for the trees. The more details of your system that you cover with tests, the more likely you are to have Robustness problems – tests that fail when these details change.  Speed obviously also suffers – the time to run the test suite usually scales linearly with the number of test cases. Updatability doesn’t necessarily get worse as the number of test cases increases, but it will if you don’t adhere to good design principles in your test code, or lack tools for bulk update of test data for example.

I think the principles are largely the same whether you’re writing skinny little unit tests or fatter functional tests that touch more of the codebase. My experience tells me that it’s a lot easier to be successful with unit tests. As the testing thickness increases, the feedback cycle gets slower, and your mistakes are amplified. That’s why I concentrate on teaching these principles through unit testing exercises. Once you understand what you’re aiming for, you can transfer your skills to functional tests.

How can you use these principles?

I find it useful to remember these principles when designing test cases. I may need to make tradeoffs between them, and it helps just to step back and assess how I’m doing on each principle from time to time as I develop. If I’m reviewing someone else’s test cases, I can point to code and say which principles it’s not following, and give them concrete advice about how to make improvements. We can have a discussion for example about whether to add more test cases in order to improve regression protection, and how to do that without reducing overall readability.

I also find these principles useful when I’m trying to diagnose why a test suite is not being useful to a development team, especially if things have got so bad they have stopped maintaining it. I can often identify which principle(s) the team has missed, and advise how to refactor the test suite to compensate.

For example, if the problem is lack of Speed you have some options and tradeoffs to make:

  • Replace some of the thicker, slower end-to-end tests with lots of skinny fast unit tests, (may reduce regression protection)
  • Invest in hardware and run tests in parallel (costs $)
  • Use a profiler to optimize the tests for speed the same as you would production code (may affect Readability)
  • Use more fakes to replace slow parts of the system (may reduce regression protection)
  • Identify key test cases for essential functionality and remove the other test cases. (sacrifice regression protection to get Speed)

Strategic Decisions

The principles also help me when I’m discussing automated testing strategy, and choosing testing tools. Some tools have better support for updating test cases and test data. Some allow very Readable test cases. It’s worth noting that automated tests in agile are quite different from in a traditional process, since they are run continually throughout the process, not just at the end. I’ve found many traditional automation tools don’t lead to enough Speed and Robustness to support agile development.

I hope you will find these principles help you to reason about your strategy and tools for functional automated testing, and to design more maintainable, useful test cases.

Images Attribution: DaPino Webdesign, Lebreton, Asher Abbasi, Woothemes, Iconshock, Andy Gongea, FatCow from www.iconspedia.com

One of the great privileges of being the programme chair for Scandinavian Developer Conference is getting to choose the keynote speakers. This year, I’m delighted to present Dan North and Janice Fraser, both thought leaders in the field of software development. Although from different backgrounds and perspectives, they’re both accomplished at building software that delivers great business outcomes. I’d like to tell you a little about each person, and why I’ve invited them to Göteborg for SDC2013.

Dan North – a man full of intriguing ideas

I first came accross Dan North at a conference in 2007, talking about a topic I was very familiar with – unit testing – but using a whole new set of words. Behaviour Driven Development (BDD) intrigued me then, and still does now. How can switching the word “Test” for “Behaviour” and “AssertEqual” to “Should be” make such a difference to the way you end up designing your code?

In his famous article from 2006, “Introducing BDD” Dan explains that he found when he stopped talking about “Testing” and started instead used the word “Behaviour”, “… a whole category of coaching problems disappeared”. People understand more easily that defining the behaviour of the software is an important activity for the whole team, not just testers. It also changes the way you as a programmer think about your code, and helps you focus on what’s important.

BDD as an approach to software development is still being actively developed and written about, although Dan himself has largely stepped aside in favour of other thought leaders like Elizabeth Keogh, Chris Matts, Olav Maasen, and of course Gojko Adzic. Gojko wrote the hugely influential book “Specification by Example” which is all about having useful conversations about software behaviour, and expressing that in terms of executable examples – ie a lot like BDD. At about the time that book was being written, Dan himself chose a different road. He actually stepped out of the consultant life entirely for about two years, taking up a full time position developing software at a financial trading firm.

His latest ideas around “Accelerated Agile” to a large extent come from his experiences working in that high-powered trading environment. He wrote in his blog: “This team was the most insanely effective delivery machine I’ve ever been a part of”, and I find that particularly intriguing. He says that standard agile practices like Continuous Integration and maintaining a Product Backlog weren’t being used! So what exactly did they do in order to be so effective?

Dan has also famously opined that “Programming is not a Craft”, and argues that the “Software Craftsmanship Manifesto … [is] a spectacularly easy bandwagon to jump on”. He says he’d rather see, “…a call to arms to stop navel-gazing and treat programming as the skilled trade that it is.” So there. Dan certainly has some strong opinions, and when I’ve met him, he always seems to express himself with wit and intelligence.

I’m really looking forward to Dan’s keynote address on Tuesday 5th March. I’m intrigued to find out what “Patterns of Effective Delivery” is all about, and to hear his latest opinions on the practice of software development.

Janice Fraser – a pioneer of Lean User Experience

To a large extent, Silicon Valley is the epicenter of our whole industry. Many of the biggest and most influential software companies in the world are based there, and as an incubator with a friendly climate for startup companies, it is unparalleled, despite the efforts of many other regions around the globe to imitate their success.

Janice Fraser has been working in Silicon Valley for over 15 years, and she says in her CVI’ve seen a lot — bubbles, bursts, and fantastic acts of collaboration that have transformed literally billions of lives.” Yes, that’s right, billions of lives.

The latest trend coming out of the Valley is “Lean Startup”, a term coined by Eric Ries, and documented in his bestselling book “The Lean Startup: How Today’s Entrepreneurs Use Continuous Innovation to Create Radically Successful Business”.  I first heard about it in 2011, when Joshua Kerievsky, an early adopter of eXtreme Programming and successful entrepreneur, published an article “Agile vs. Lean Startup”. He says, “[Lean Startup] rocks. It rocks far more than Agile.” If it rocks far more than agile, then I find that pretty intriguing!

Janice Fraser is of course also an early adopter of “Lean Startup”, and has pointed out that the ideas in it are not all new. She saysThe Lean Startup, is a rediscovery of user centered design… [it] gives UX teams an unqualified mandate to make products customers love.

Janice herself is a serial entrepreneur, having led several startup companies. She says in her CV, “My proudest success is Adaptive Path, a leading product design firm. I was a founder and served as the company’s first CEO”. Adaptive Path is still successfully in business.

Janice is not shy about recounting her failures either, she’s written a candid report of how she started “Emmet Labs” in 2007 intending to change the world, right through to when she laid off all the staff in 2009. I think her article “7 things I did right with Emmet Labs” shows how much courage and determination it takes to build a company, and how resilient and clear-thinking Janice herself can be in a crisis.

Janice’s business these days is helping other startup companies to succeed: “Before you build anything, find customers, learn their needs & goals, and measure your progress towards your vision” – an extract from the marketing materials for her company, Luxr. She’s also just about to publish a book “The Lean Product Book: How Smart Teams Work Better”, which I guess will document the kind of advice she gives to her clients – all about Lean User Experience.

All this talk of startups and product development in Silicon Valley might seem a long way from chilly Göteborg and our IT industry, dominated by a few huge corporations. I think it’s just the kind of thing we need to hear about, though. Companies of any size need to renew themselves and develop great new products in order to flourish, and this is clearly an area where Janice is innovating and leading the world. I’m really looking forward to hear what she’s going to say in her keynote “Lean Startup Product Teams: Principles of Success”, on Monday 4th March.

The Cyber-Dojo tool was designed by Jon Jagger as en environment where you can practice your coding skills. I’ve used it a few times now with groups at coding dojos and code retreats, and I think it’s a pretty useful tool for those contexts. (See also my last post which talks about using Cyber-Dojo during Global Day of Code Retreat).

One of the advantages of Cyber-Dojo for a Coding Dojo, (or Code Retreat), is that you don’t waste much time at the start of a coding session setting up a coding environment. The session facilitator creates a Cyber-Dojo instance in advance, and puts the practice-id up on a whiteboard or projector where everyone can see it. Participants just point their browsers at cyber-dojo.com, enter the practice-id, and very quickly get coding.

Cyber-Dojo supports about a dozen programming languages, and has starting positions set up for about 30 code katas. What is less known, is that it also allows you to set up any kata or starting position you like. I thought I’d take this opportunity to create some documentation for this feature:

  1. create a new cyber-dojo instance by going to http://cyber-dojo.com/ and pressing “setup”
  2. Select the programming language you want to use
  3. Select “Verbal” from the list of katas
  4. Click “OK”, then make a note of the “practice-id” – it’s also in the url. Press “Start” to enter this cyber-dojo instance.
  5. Edit the code files with your starting position, and update the instructions with the details of the kata exercise. Basically get the cyber-dojo instance set up to the position you want people in your Coding Dojo to start from. Run the tests as often as you like until you have everyting as you want it.
  6. Click on the “fork” icon on the left hand side to create a new cyber-dojo instance starting from this position, and note the new practice-id. You can give this id to your Coding Dojo participants.
  7. You can also publish a url that will automatically create a new cyber-dojo instance from this position, so people can create their own cyber-dojo instances. The form of the url is:
http://cyber-dojo.com/forker/fork/(practice-id)?avatar=(your animal)&tag=(number of the traffic light to fork)

I’ve used this feature to set up a number of Refactoring katas in cyber-dojo, for example the Tennis kata:

Perhaps sometime Jon will add a page on cyber-dojo.com that lists these kinds of additional available starting posistions, (hint!), but for now, you’ll have to keep track of them yourself.

By the way, do let me know if you try out this Tennis Refactoring Kata in Cyber-Dojo and how you get on with it. I welcome comments on this blog or on my github repo.