Unit test patterns, Episode I : A foundation emerges

Learning TDD has been a lot of work. I’ll start by saying that. If you’re new to TDD, you’re probably floundering around a bit. I did. A lot. I think the main, underlying issue is to “see the layers,” specifically just the one layer you’re writing a test for. Before TDD, I saw an application as more of a big unit with a few large layers. This really causes a struggle when writing a test. TDD really pressures you (drives you ;-)) to see the small, incremental steps. It’s seeing those little steps that’s the trick. If you bite off too much of an application to unit test because you’re a power coder that “get’s things done,” then writing that test becomes like trying to put your shoes on without untying them. It will frustrate you to no end. I’ve been there and done that.  But don’t get rid of the laces. Just untie the shoes. This is what kept me from giving up on TDD– something about it just felt right and smarter folks than me were doing it. Now, I’m no lemming, blindly following all the latest fads, but, well, I’m no lemming blindly following the status quo either. And to be fair, TDD is far too old to be a fad.

And I’m certainly still learning– I’m young to TDD– just barely over a year old now. I had tried it a few times before and couldn’t quite get off the ground, so I took a weekend at home and locked myself in a room until I wrote some successful tests. That’s when I finally got started and I’ve used it on my most recent project at work: a new website (ASP.Net MVC). Perhaps someday I’ll write about how to start a project with TDD, but for now I just want to share a few testing patterns I’m currently using. Feel free to critique; I’m on a journey– “Give instruction to a wise man, and he will be still wiser; Teach a just man, and he will increase in learning.”

So, about those patterns. This post will look at the basic one which is all about

  • a process
  • a situation
  • and expectations

This fits well with Arrange, Act, and Assert for the mechanics of the tests/specs, and all the formats share this overarching design or structure which ends up looking like this

namespace Process
{
   public class Situation
   {
      public void Expectation()
      {}
   }
}

I like the BDD naming convention and totally favor a perspective of “specifying behavior” rather than “passing tests.” In the past, I’ve used “When” to declare the process and “Given” to declare the situation. Because of this, I typically reorder the classic “Given-When-Then” naming pattern to “When-Given-Then.”

I’ll take a recent real world (and common) situation for an example: a web site where a user who has an account may invite others to join that account. I’ll call this a UserInvitationManager (for this post).

I feel using the “When” first to declare the activity/process establishes the context quickly. So…

namespace When_inviting_a_user_to_join_an_account
{
}

The situation is limited to just the input parameters in this case, so…

namespace When_inviting_a_user_to_join_an_account
{
   [TestFixture]
   public class Given_an_email_address_and_an_account_number
   {
   }
}

Before I move on to the “Then,” I set up for those Thens. This can be most of the work, actually, as you’ll see. Most of the time, I put the Act(ing) into the TestFixtureSetup method rather than inside the Test method. I do this so that each TestFixture specifies the behavior for one situation and has the chance to easily Assert many things after the single Act(ion). By no means am I married to this. If a situation serves me better to re-Act before every Assert(ion), I’ll do it in an instant. But otherwise, I’ll Act once, which keeps the Assert(ion)s very simple.

So to set up, I first need to define and initialize the actors involved, including the system under test, or in other words, the process for which I’m specifying behavior. And like I said, I’m skipping some of the “TDD-how-to,” so I won’t go into how I came up with the dependencies for the UserInvitationManager. But I will go ahead and Act at the end of the setup.

namespace When_inviting_a_user_to_join_an_account
{
   [TestFixture]
   public class Given_an_email_address_and_an_account_number
   {
      UserInvitationManager invitationMgr;
      IUserInvitationSender invitationSender;
      IAccountManager accountMgr;

      String emailAddress;
      String accountNumber;

      [TestFixtureSetup]
      public void SetupTestFixture()
      {
         // Arrange
         invitationSender = MockRepository.GenerateMock<IUserInvitationSender>();
         accountMgr = MockRepository.GenerateMock<IAccountManager>();
         invitationMgr = new UserInvitationManager(invitationSender, accountMgr);
         emailAddress = "newUserEmail@doesntmatter.stilldoesntmatter";
         accountNumber = "doesntMatterEither";

         //Act
         invitationMgr.InviteUser(emailAddress, accountNumber);
      }
   }
}

So, a lot of code, relatively speaking, just got added. For me, arranging is defining your parties and intializing them.

I generally define four groups of parties:

  • system under test (the UserInvitationManager)
  • dependencies (the invitationSender and accountMgr)
  • parameters (the emailAddress and accountNumber)
  • result (this action returned no result, but if it did, I would have set the result variable during the Act)

Then I initialize them.

To keep things separated in the above example, I initialized them in the setup method, but most times I initialize what I can on definition to reduce unnecessary loc.

IAccountManager accountMgr = MockRepository.GenerateMock();

Purely a preference. Perhaps a TDD puritan would refuse, but once I got used to this format, I didn’t need to always separate the definition and intialization, and I found that it cleans up some stuff for other setup efforts, like stubbing dependencies.

Now we get to the “Thens.” And, thanks to Ayende and RhinoMocks, they’re short and sweet, as, I think, they should be. Also notice one Assert per Test. Yeah, I’m generally one of those.

namespace When_inviting_a_user_to_join_an_account
{
   [TestFixture]
   public class Given_an_email_address_and_an_account_number
   {
      UserInvitationManager invitationMgr;
      IUserInvitationSender invitationSender;
      IAccountManager accountMgr;

      String emailAddress;
      String accountNumber;

      [TestFixtureSetup]
      public void SetupTestFixture()
      {
         // Arrange
         invitationSender = MockRepository.GenerateMock<IUserInvitationSender>();
         accountMgr = MockRepository.GenerateMock<IAccountManager>();
         invitationMgr = new UserInvitationManager(invitationSender, accountMgr);
         emailAddress = "newUserEmail@doesntmatter.stilldoesntmatter";
         accountNumber = "doesntMatterEither";

         //Act
         invitationMgr.InviteUser(emailAddress, accountNumber);
      }

      [Test]
      public void Then_the_user_invitation_manager_should_pre_register_that_email_address_to_the_account()
      {
         accountMgr.AssertWasCalled(acctMgr => acctMgr.PreRegisterByEmailAddress(accountNumber, emailAddress));
      }

      [Test]
      public void Then_the_user_invitation_manager_should_send_an_invitation_to_the_given_email_address()
      {
         invitationSender.AssertWasCalled(sender => sender.SendInvitation(emailAddress));
      }
   }
}

Pretty basic, but again:

  • One [TestFixture] per situation as generally defined (“Given”) by parameters. Sometimes, the situation is additionally defined by a result from calling a dependency.
  • Usually one Act(ion) per situation. Sometimes this is not possible or preferable, and when it’s not, I don’t cry about it.
  • One Assert(ion) per [Test] method.

That’s the foundational pattern that has emerged for me and it’s good for many of my specifications. In a future post, I’ll actually change up how I name some of these elements, like the Whens and the Thens and even the system under test. See the previous post for a hint. But upon this basic structure I can easily define more complex situations. So, it’s been a little over a year for TDD/BDD and me, and this is where I am…headed.

Now read Unit test patterns, Episode II : Inheritance strikes back.

Coding forwards

So I’ve been drinking the dependency injection Kool-Aid for a while now and it got me thinking about the way I represent business logic in code. Maybe I’ve just come back to the basics of 50yr old programming, but that’s ok because the basics are the basics. And I think they’re this: you’ve got Data and you’ve got Processes. So how did dependency injection (with an IoCContainer/DependencyResolver) get me here? (Skip this long story by jumping to the asterisks *******)

3 words: inversion of control. They flip (invert) the whole development process on it’s head…or maybe it’s been upside down this whole time and it’s flipped it on it’s feet. I suspect so. I used to do my analysis and start coding the data access components: writing queries, building classes and server-side processes to return this data to a client that would utilize it. Now, I start with the top of the application.

I can do this because my dependencies are abstractions that don’t have to be implemented for the consumer to be completed or even for the project to compile. The reason I do this is because it keeps me on target. I’m not building some large infrastructure back-end that ends up being a few pieces of data off. Those can be big things to fix. But by starting with the application, I know exactly what the next layer down needs to do. There’s almost no mystery at all. It feels like I’ve been driving backwards this whole time and now I’ve finally turned my truck around.

And here’s where that meets with a new fixation on “processes.” Because I start at the top, I easily recognize these big tasks to do. If the application had a “Do the yard work” feature, these big tasks would be “mow the yard,” “weed eat,” and “blow off the drive way”. These tasks are the processes. In business perhaps they’d be stuff like “bill the customer” or “report a claim.” Immediately, I see how this flows naturally with the language of my business customers and I like that…a lot.

So in my backwards driving days, because I was working from the inside out, I’d notice that lots of data and processes were related and I’d package them up inside a single class. This lead to sizable classes, sometimes with many methods, often methods that I’d create because they seemed like they could be handy even though I didn’t know of a specific case that needed it. Remember, I was driving backwards from the supposed data to the application. Who knows what I might need? In reality, seldom would any one consumer use all these methods. Typically, the consumer instantiated the class for just one method.

**********************************************
**********************************************

But driving forward I see clearly what methods I actually need and I make just those. But make them where? In an interface, of course! “Bill the customer” becomes a BillCustomer() method inside the interface ICustomerBiller. “Report a claim” becomes ReportClaim() inside IClaimReporter. I was initially super excited about the separation and independence of the interfaces, but their definitions seemed a bit…contrived. ICustomerBiller? I saw that I was trying to make a noun out of all these processes, usually by swapping the words and adding an “er.” Works great, but these phony nouns seem hokey, and at times even vague. Definitely not going for vague. Then I thought, ** I don’t even need the noun! ** I’m just interested in the process. So then came IBillCustomerProcess. I love how the name is clear, the declared dependencies are equally clear (x process depends on IBillCustomerProcess), and the unit tests become clear (The BillCustomerProcess should invoke the CreateInvoiceProcess).

Excellent. But by now someone is crying, “But the name and method sound so redundant: BillCustomerProcess.BillCustomer()???” Yes, it is redundant, at least from a consumer’s point of view. The redundancy in the eyes of the consumer bothers me. I really just want to say something like “do the BillCustomerProcess.” Returning to my unit test (+1 for TDD), one process needs to call or “invoke” another process…hmmm, invoke sounds like delegates to me. What if I could depend on a delegate? Then the consumer could just BillCustomerProcess.Invoke(), or even .BeginInvoke for easy multi-threading stuff. Cool. At this point I laugh at myself. This is probably in a number of freshmen level textbooks somewhere for classes I never took. Oh well, better late than never.

So now I’m experimenting with delegate dependencies. Up front, my biggest uneasiness is that the delegate displaces the need for an interface. And I really like interfaces. They’ve become a kind of security blanket. I suppose I just really like abstraction and delegates are abstractions, but it doesn’t feel safe yet. That, and the IoC Container registration looks ugly. And I’m not sure other consequences there might be.

I still must have my IoC Container, of course, to auto-wire these dependencies. No compromise there. So here’s some example code of how I did that…

First, the process will be a simple “print message” process defined like so…

public delegate void PrintMessageProcess();

Next, my TestClass will declare the dependency in its constructor…

public TestClass( PrintMessageProcess printMessageProcess )
{
   _printMessageProcess = printMessageProcess;
}

I still have to write a function in a class somewhere, so I’ll do that…

public class PrintClass
{
   public void Print()
   {
      Console.WriteLine( "Hello world." );
   }
}

Then the ugly part, registering it in an IoC Container. I’ll use StructureMap here…

x.For<PrintMessageProcess>().Use( () => ObjectFactory.GetInstance<PrintClass>().Print );

Finally, somewhere in my TestClass…

public void RunTest()
{
   _printMessageProcess.Invoke();
}

And that’s it.

One of the things I really like is that the implementation doesn’t have to know anything about the delegate, which is unlike interfaces. This could make breaking down legacy code easier since the classes wouldn’t have to reference anything. The only one that knows what’s going on is the IoC Container.

One of the things I don’t like is that the implementation doesn’t have to know anything about the delegate, which is unlike interfaces. 😀 This could make for unintended behavior since the implementation is not subject to a defined contract. Scary.

If anybody actually read this far, any thoughts?

First blog post ever

Why? Creative outlet, I suppose, and to understand my own ideas and others better. Communicating ideas is often a great way of learning them more deeply yourself. And who knows, perhaps I’ll even get a comment to correct my thinking. After all, “The first to present his case seems right, till another comes forward and questions him.”  So hello, world. Feel free to question me.