I’ve now been to Keith Braithwaite’s TDD as if you meant it session twice and also ran a series of coding katas in this style at work using Conway’s Game of Life.

Here’s the concept:

1) write exactly ONE failing test
2) make the test from (1) pass by first writing implementation code IN THE TEST
3) create a new implementation method/function by:
3.1) doing extract method on implementation code created as per (2), or
3.2) moving implementation code as per (2) into an existing implementation method
4) only ever create new methods IN THE TEST CLASS
5) only ever create implementation classes to provide a destination for extracting a method created as per (4).
6) populate implementation classes by doing move method from a test class into them
7) refactor as required
8 ) go to (1)

What I’ve learnt

  • It’s really hard to get going.
  • At first it feels ridiculous and pointless effectively testing things like true == false and having the code under test actually in the fixture.
  • A recurring theme has been throwing away lots of code. Focusing on trying to do the simplest possible thing often means your understanding and your solution frequently changes and continuously becomes redundant. It’s a very frustrating experience.
  • I don’t think it’s at all a practical way to write production code.

If I’m not going to use it what’s the point?

As Keith has repeatedly stated, he would not recommend you went back to your job and started coding this way. What it is though is an excellent training exercise, the equivalent of a musician practicing scales. It emphasises the core principles of TDD more than anything else I’ve tried or read.

Therefore I’d highly recommend it as something to do on a relatively regular basis to help refresh your TDD muscle memory and it’s a great way to introduce the concepts of TDD to the uninitiated.

As Queen Elizabeth II once said, “It’s all to do with the training: you can do a lot if you’re properly trained.”

Sometimes we want to test some really nasty legacy code but are inhibited by constructors taking tricky things like HttpWhatevers, God objects and so on which you do not care about but would require enormous effort setting up just to try and get an instance of the damn thing so you can test your method.

One way out is to create a parameterless constructor on the class which is only used for testing. Not at all nice, but sometimes necessary to create that first seam.

A candidate I was pair interviewing with introduced me to something which may prove preferable in these cases – the Microsoft serialization library has a method which will initialize a class without calling the constructor:

FormatterServices.GetSafeUninitializedObject
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatterservices.getsafeuninitializedobject.aspx

This way you don’t have to modify the code!

I would only ever advise using this if your only other sensible option would be to override the constructor. Hopefully once you have your tests you would be able to confidently refactor out the problematic code.

I’ve been coding in the Behaviour Driven Development (BDD) style for a while now and thought I’d share my syntax at the state it has currently evolved to. Briefly, the idea behind of BDD is to have clear definition of business intent within your code, particularly your unit tests. The benefits are it’s easier to see what your system is supposed to be doing and your tests are more closely associated to the required behaviour of the system rather than the implementation, ergo, behaviour driven.

I originally started by making an effort to write my tests method names as sentences starting with “should” (e.g. should_set_active_status_to_false_when_status_updated), but having used the “Given, When, Then” format for our automated acceptance tests I’ve been trying to move more in this direction.

For a start, I’ve being using the Visual Studio solution explorer to help. Previously tests would be organised something like this:

tests organised in explorer non bdd style

Which I have replaced with this:

using solution explorer to help describe tests

As you can see I’m using folders and file names to help give the tests context. One major advantage of this is as the tests are less coupled to the implementation of the system under test (SUT) any changes to the implementation are less likely to require moving tests around so the intent remains intact. The other obvious advantage is the intended behaviour is much clearer.

The next thing to show you is the tests:

The nice thing here is the namespace is taken from the folder and the class name from the file name so I’m getting a nice convention (even if it is being obfuscated by C# scaffolding). In this example I’m still sticking to the “should” convention but below I went for something a bit different:

So this is a little different because the conditions are more specific. There’s another class for non view direct users so I split them up, partly so the test method names needn’t be so long but mainly because it’s easier to understand what’s going on. Purists may feel uncomfortable with my relative lack of a standardised syntax, but the most important thing to me is it’s easy to see what’s going on and beyond that I don’t particularly care how you say it.

What this really is is a feeble attempt to mimic the elegance you get from RSpec (which we’ve been using along with Cucumber & Watir to write our automated tests). I was thinking today whilst I was playing with this that I don’t just want to mimic RSpec I actually want write my unit tests using RSpec. Excitingly it looks like the DLR and IronRuby will make this possible. Up until now I’d been struggling to think of a really appropriate use of a dynamic language within the .Net context but not any more.

One of the less stated benefits of doing TDD is that it concentrates your mind on the problem.

Recently I was looking at a section of code which was creating a Lucene search string from criteria passed in from the user. I needed to add some new functionality, but it was a bit higgledy-piggledy so following the broken windows principle I decided to refactor it to the builder pattern before I added my new feature.

I ran NCover on the code and it reported 70% coverage which considering what I knew about the history of the system was surprisingly high. I decided there was enough coverage, paired with a colleague and dived in. At first we were doing well. Our changes broke the tests a few times which reassured us about the coverage, but after a while it felt that we were losing a bit of steam. We’d done a lot of refactoring but it didn’t feel like we’d got very far.

Skip to a couple of days later – I’d not been able to touch the code and neither had my colleague who had now been taken off to deal with another project, so I pulled in the other dev on my team who is probably the most fanatical TDD nut I’ve ever met. Immediately he was uncomfortable, he’d quickly spotted the tests were really only integration tests (something I had put to the back of my mind) and got jittery as we continued from where I’d left off. I didn’t like to see him in so much pain so quickly relented and let him write new tests even though I felt it was just going to slow us down, maybe even to the point where we wouldn’t get it finished. However he assured me that although it felt slow now we’d be racing along soon enough.

Not only was he right about that, but as we were doing it the objective was so much clearer. Writing the new tests meant we were forced to really think about each move we made so our refactoring had clear direction. We spent about the same time working on the problem but probably made twice as much progress as my previous attempt and ended up with a proper unit test suite around the code.

Some day soon people are probably going to do away with the need to do TDD, which I think will be a shame as it never ceases to amaze me how many benefits it has.

I’ve recently started using RhinoMocks instead of nMock, mainly because it’s strongly-typed. However, I’ve found a few other little treats:

Stubs

In nMock, if you want to stub some method calls on a mocked interface you have to do something like this:

Mockery mockery = new Mockery();
IService mockService = mockery.NewMock();
Stub.On(mockService).Method("MethodA");
Stub.On(mockService).Method("MethodB");
Stub.On(mockService).Method("MethodC");
...

Which is cumbersome and noisy. In RhinoMocks you can do this:

MockRepository Repository repository = new MockRepository();
IService serviceMock = repository.Stub();
...

…and RhinoMocks will ignore all calls to that interface. This is really nice as you generally only test the SUT’s interaction with one dependency at a time.

Dynamic Mocks

If you only want to test one interaction with a dependency and ignore all others you can create a dynamic mock.

MockRepository Repository repository = new MockRepository();
repository .DynamicMock();
...

All calls to the mocked dependency will be ignored unless they are explicitly expected (e.g. Expect.Call(mockService.MethodA)…..). This is the same as not saying mockery.VerifyAllExpectationsHaveBeenMet() in nMock. It’s always annoyed me that you have to remember to do this in nMock and I much prefer that the default for RhinoMocks is to fail when encountering an unexpected method call.

Raising Events

nMock does not natively support raising events, which is a pain, but there are ways around it (I’ve extended his example to support custom EventArgs which you can download here). With RhinoMocks it’s much simpler. Rather than explaining it myself, check out J-P Boodhoo’s great example here.

I’ve being doing TDD for a year or so and the part I have struggled with the most is testing private methods. Should you test them at all? If so, how do you test them?

Michael Feathers’ book “Working Effectively with Legacy Code” has this to say about it:

“This question comes up over and over again from people new to unit testing: “How do I test private methods?”. Many people spend a lot of time trying to figure out how to get around this problem, but [...] the real answer is that if you have the urge to test a private method, the method shouldn’t be private; if making the method public bothers you, chances are, it is because it is part of a separate responsibility: it should be on another class.”