Showing posts with label Testing. Show all posts
Showing posts with label Testing. Show all posts

Tuesday, November 20, 2007

Stop the madness

I've been extending a legacy codebase lately to make it a bit more testable, and a few small, bad decisions have slowed my progress immensely.  One decision isn't bad in and of itself, but a small bad decision multiplied a hundred times leads to significant pain.  It's death by a thousand cuts, and it absolutely kills productivity.  Some of the small decisions I'm seeing are:

  • Protected/public instance fields
  • Inconsistent naming conventions
  • Try-Catch-Publish-Swallow
  • Downcasting

The pains of these bad decisions can wreak havoc when trying to add testability to legacy codebases.

Public/protected instance fields

One of the pillars of OOP is encapsulation, which allows clients to use an object's functionality without knowing the details behind it.  From FDG:

The principle states that data stored inside an object should be accessible only to that object.

Followed immediately by their guideline:

DO NOT provide instance fields that are public or protected.

It goes on to say that access to simple public properties are optimized by the JIT compiler, so there's no performance penalty in using better alternatives.  Here's an example of a protected field:

public class Address
{
    protected string zip;

    public string Zip
    {
        get { return zip; }
    }
}

public class FullAddress : Address
{
    private string zip4;

    public string Zip4 
    {
        get
        {
            if (Zip.Contains("-"))
            {
                zip4 = zip.Substring(zip.IndexOf("-") + 1);
                zip = zip.Substring(0, zip.IndexOf("-"));
            }
            return zip4;
        }
    }
}

There was an originally good reason to provide the derived FullAddress write access to the data in Address, but there are better ways to approach it.  Here's a better approach:

public class Address
{
    private string zip;

    public string Zip
    {
        get { return zip; }
        protected set { zip = value; }
    }
}

I've done two things here:

  • Added a protected setter to the Zip property
  • Changed the access level of the field to private

Functionally it's exactly the same for derived classes, but the design has greatly improved.  We should only declare private instance fields because:

  • Public/protected/internal violates encapsulation
  • When encapsulation is violated, refactoring becomes difficult as we're exposing the inner details
  • Adding a property later with the same name breaks backwards binary compatibility (i.e. clients are forced to recompile)
  • Interfaces don't allow you to declare fields, only properties and methods
  • C# 2.0 added the ability to declare separate visibility for individual getters and setters

There's no reason to have public/protected instance fields, so make all instance fields private.

Inconsistent naming conventions

Names of classes, interfaces, and members can convey a great deal of information to clients if used properly.  Here's a good example of inconsistent naming conventions:

public class Order
{
    public Address address { get; set; }
}

public class Quote : Order
{
    public void Process()
    {
        if (address == null)
            throw new InvalidOperationException("Address is null");
    }
}

When I'm down in the "Process" method, what is the "address" variable?  Is it a local variable?  Is it a private field?  Nope, it's a property.  Since it's declared camelCase instead of PascalCase, it led to confusion on the developer's part about what we were dealing with.  If it's local variable, which the name suggests, I might treat the value much differently than if it were a public property.

Deviations from FDG's naming conventions cause confusion.  When I'm using an .NET API that uses Java's camelCase conventions, it's just one more hoop I have to jump through.  In places where my team had public API's we were publishing, it wasn't even up for discussion whether or not we would follow the naming conventions Microsoft used in the .NET Framework.  It just happened, as any deviation from accepted convention leads to an inconsistent and negative user experience.

It's not worth the time to argue whether interfaces should be prefixed with an "I".  That was the accepted convention, so we followed it.  Consistent user experience is far more important than petty arguments on naming conventions.  If I developed in Java, I'd happily use camelCase, as it's the accepted convention.

Another item you may notice as there are no naming guidelines for instance fields.  This reinforces the notion that they should be declared private, and the only people who should care about the names are the developers of that class and the class itself.  In that case, just pick a convention, stick to it, and keep it consistent across your codebase so it becomes one less decision for developers.

Try Catch Publish Swallow

Exception handling can really wreck a system if not done properly.  I think developers might be scared of exceptions, given the number of useless try...catch blocks I've seen around.  Anders Heljsberg notes:

It is funny how people think that the important thing about exceptions is handling them. That is not the important thing about exceptions. In a well-written application there's a ratio of ten to one, in my opinion, of try finally to try catch. Or in C#, using statements, which are like try finally.

Here's an example of a useless try-catch:

public class OrderProcessor
{
    public void Process(Order order)
    {
        try
        {
            ((Quote)order).Process();
        }
        catch (Exception ex)
        {
            ExceptionManager.Publish(ex);
        }
    }
}

In here we have Try Catch Publish Swallow.  We put the try block around an area of code that might fail, and catch exceptions in case it does.  To handle the exception, we publish it through some means, and then nothing.  That's exception swallowing.

Here's a short list of problems with TCPS:

  • Exceptions shouldn't be used to make decisions
  • If there is an alternative to making decisions based on exceptions, use it (such as the "as" operator in the above code)
  • Exceptions are exceptional, and logging exceptions should be done at the highest layer of the application
  • Not re-throwing leads to bad user experience and bad maintainability, as we're now relying on exception logs to tell us our code is wrong

Another approach to the example might be:

public class OrderProcessor
{
    public void Process(Order order)
    {
        Quote quote = order as Quote;
        
        if (quote != null)
            quote.Process();
    }
}

The only problem this code will have is if "quote.Process()" throws an exception, and in that case, we'll let the appropriate layer deal with those issues.  Since I don't any resources to clean up, there's no need for a "try..finally".

Downcasting

I already wrote about this recently, but it's worth mentioning again.  I spent a great deal of time recently removing a boatload of downcasts from a codebase, and it made it even worse that the downcasts were pointless.  Nothing in client code was using any additional members in the derived class.  It turned out to be a large pointless hoop I needed to jump through to enable testing.

Regaining sanity

The problem with shortcuts and knowingly bad design decisions is that this behavior can become habitual, and the many indiscretions can add up to disaster.  I had a high school band director who taught me "Practice doesn't make perfect - perfect practice makes perfect."

By making good decisions every day, it becomes a habit.  Good habits practiced over time eventually become etched into your muscle memory so that it doesn't require any thought.  Until you run into a legacy codebase that is, and you realize how bad your old habits were.

Wednesday, November 14, 2007

A downcasting tragedy

And now, for another tale of legacy code woe, here's a gut-wrenching tragedy of OCP and downcasting, in five acts.

Exposition

We have a feature we're implementing that when the store's configuration settings allow for a survey link to be shown, it should show up, otherwise, it shouldn't.  We put these settings in a simple interface (cut down for brevity):

public interface ISettings
{
    bool ShowSurvey { get; }
}

Settings can come from many places, such as configuration files, database, or web service.  This is a pretty nice example of OCP, as our app is open for extension for different "ISettings" implementations, but closed for modification as someone can't decide to use something else besides "ISettings".  Since we have an interface, the source doesn't matter.

We manage access to the settings through a static class:

public static class StoreContext
{
    public static ISettings Settings { get; set; }
}

Actual instances are set during early in the ASP.NET pipeline, so later stages have that information.  The original ISettings implementations are stored in ASP.NET Session.

Now, we need to provide functional and regression tests for this feature, using Selenium.

Rising action

To help with functional and regression tests, I'm employing the record and playback state technique I mentioned earlier.  I create an "ISettings" implementation that can be serialized and deserialized into XML, which helps when I want to manually edit the settings:

[XmlRoot("Settings")]
public class SettingsDto : ISettings
{
    public SettingsDto() { }

    public SettingsDto(ISettings settings)
    {
        ShowSurvey = settings.ShowSurvey;
    }

    public bool ShowSurvey { get; set; }
}

My "download.aspx" page combines both the cart and the settings information into a single DTO, and streams this file to the client.  In my "replay.aspx" page, I take the XML, deserialize it, and put it into Session.  Finally, I redirect to the "shoppingcart.aspx" page, which pulls the ISettings implementation out of Session and sets the StoreContext variable to my deserialized SettingsDto instance.

This is all fairly straightforward, and I'm pretty happy about this solution as I can now plug in any settings I like and verify the results through automated tests.  As it is with all legacy code, things just aren't that simple.

Climax

Running the code the first time, downloading and replaying goes smoothly, and all of my values are serialized and deserialized properly as my unit tests prove.  However, when I get redirected to the "shoppingcart.aspx" page, I get a distressing exception:

System.InvalidCastException:
  Unable to cast object of type 'BusinessObjects.SettingsDto'
  to type 'BusinessObjects.DbSettings'.

The dreaded invalid cast exception, something is making some really bad assumptions and killing my code.

Falling action

Just when I thought I was making progress, the InvalidCastException came up and crushed my dreams.  Looking at the stack trace, I see that my the exception is coming from the base Page class that all pages in our app derive from.  Here's the offending code:

public abstract class StorePage : Page
{
    protected DbSettings Settings
    {
        get { return (DbSettings)StoreContext.Settings; }
    }
}

A convenience property on the base class allowed derived classes to get at the static ISettings instance.  But on closer inspection, this property is downcasting the ISettings instance coming out of StoreContext to DbSettings.  Downcasting is when you cast to a derived type from an instance of a base type.  That's a fairly large assumption to make, though.  How do I know for sure that the instance is really the derived type, and not some other derived type of the base type?  I can't guarantee that assumption holds, as this example shows.

To make things worse, it explicitly casts instead of using the C# "as" operator (TryCast for VB.NET folks).  At least then it won't fail when trying to downcast, it would just be null.  Using the "as" operator is perfectly acceptable as a means of downcasting.  I try to avoid it, as it can be a smell of Inappropriate Intimacy.

Because the code assumes that the ISettings instance is actually seriously for realz a DbSettings instance, I can never take advantage of OCP and swap out different "ISettings" implementations.  Quite depressing.

Denouement

As an experiment, and because I have a nice automated build process, I can just try to change the type referenced in the StorePage class to ISettings instead of DbSettings.  Luckily, the build succeeded and I kept the change.

If it had failed and clients absolutely needed DbSettings, I might have to look at pushing up methods to the ISettings interface, if it's possible.  If I have access to ISettings that is.  If I don't, well, I'm hosed, and my denouement would turn into a catastrophe.

The moral of this story is:

Avoid downcasting, as it makes potentially false assumptions about the underlying type of an object.  Use the "as" operator instead, and perform null checking to determine if the downcasting succeeded or not.  We can then perform safe downcasting and avoid using exceptions as flow control.

Monday, November 12, 2007

Coding without confidence

As a favor to my wife, I developed an Excel application to help her employer out with scheduling and status in a small wood manufacturing shop.  Excel was chosen as it was the lowest barrier to entry, and the quickest to get out the door.  It wasn't a mission-critical app and I wasn't getting paid or anything, so I thought I could get something delivered fairly easily.

After all, what was needed was "no big deal" and "we just need something that works".

The final solution used a lot of hidden columns to calculate intermediate results, and macros to make it easier for the end user to interact with the spreadsheet.  The problem is that there are absolutely zero tests on anything, nor can their ever be.  There's no such thing as "ExcelUnit".  I found a "VBAUnit", but it was last released over 4 years ago.

For a while, I couldn't figure out why I was so worried about releasing (i.e., emailing them a copy) the Excel app.  I realized that I had been coding without any confidence that what I was delivering worked, and would continue to work.

I've been so accustomed to having tests and automated builds as my backup, coding without them felt dirty and a little scary.  I was asked "so does it work?" and my only answer was "I hope so".  I was entrenched in "CyfDD", or "Cross-your-fingers Driven Development".  Does it work?  I dunno, better cross your fingers.  CyfDD is a close cousin of "GoykapDD", or "Get-on-your-knees-and-pray Driven Development".  Releasing only once per year or two leads to GoykapDD.

Sometimes I get asked why I bother with automated tests and builds.  Frankly, without automated tests and builds, I have zero confidence in my code.  Nor should I, or should anyone else for that matter.  Confidence in code written without automated tests and builds is just delusion.

Friday, November 2, 2007

Record and playback state in ASP.NET

Most ASP.NET applications hold various state objects in Session, Application, or other stateful mediums.  For regression testing and defect reproducing purposes, often I want to capture the exact state of these objects and replay them back at a later time, without needing to walk through the exact steps needed to setup that state.  For many defects, I don't know how the state got to where it was, I just know what the state is, so I need a mechanism to record it and play it back.

I can record and playback the state by first capturing the state by downloading a serialized version of the object, and then play it back later by uploading the serialized object file and resuming the application.

Recording state

The basic principle for recording state is that I'd like to serialize one of my state objects and allow the client to download the serialized object as a file.  With direct access to the output stream of the HttpResponse, this turns out to be fairly trivial.

Setting up the state

First, we need some sort of state object.  I'm not too creative, so here's a Cart and Item object, optimized for XML serialization:

public class Item
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public int Quantity { get; set; }
    public decimal Price { get; set; }
}

public class Cart 
{
    public Guid Id { get; set; }
    public string CustomerName { get; set; }

    [XmlArray(ElementName = "Items"), XmlArrayItem(ElementName = "Item")]
    public Item[] Items { get; set; }
}

Normally I don't put read/write arrays, but to demonstrate the easiest possible serialization scenario, that will do.  For more difficult scenarios, I usually implement IXmlSerializable or provide a separate DTO class strictly for serialization concerns.

In my Default.aspx page, I'll provide a simple button to download the cart, and some code in the code-behind to create a dummy cart and respond to the button click event:

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Cart cart = new Cart();

        cart.Id = Guid.NewGuid();
        cart.CustomerName = "Bob Sacamano";
       
        Item item = new Item();
        item.Id = Guid.NewGuid();
        item.Name = "Toothpicks";
        item.Price = 100.50m;
        item.Quantity = 99;

        Item item2 = new Item();
        item2.Id = Guid.NewGuid();
        item2.Name = "Ceramic mug";
        item2.Price = 5.49m;
        item2.Quantity = 30;

        cart.Items = new Item[] { item, item2 };

        Session["Cart"] = cart;
    }

    protected void btnDownloadCart_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/download.aspx");
    }
}

Now that I have a Cart object, I need to fill in the "download.aspx" part to allow downloads of the cart.

Outputting state to HttpResponse

The HttpResponse object has a couple of ways to access the raw byte stream sent to the client.  The first is the OutputStream property, which gives me access to a raw Stream object.  Streams are used by a multitude of objects to write raw bytes, such as serializers, etc.

I don't normally use it when I want the end-user to save the file.  If I'm creating a dynamic image or such, I can go directly against the OutputStream, but an alternate way is to use the HttpResponse.BinaryWrite method.  This will allow me to buffer content as needed, and more importantly, provide buffer size information to the end user.  That's especially important for the various browser "download file" dialogs.

Here's my Page_Load event handler for the "download.aspx" page:

   1:  protected void Page_Load(object sender, EventArgs e)
   2:  {
   3:      Cart cart = Session["Cart"] as Cart;
   4:   
   5:      if (cart == null)
   6:      {
   7:          Response.Write("cart is null");
   8:          Response.End();
   9:          return;
  10:      }
  11:   
  12:      try
  13:      {
  14:          MemoryStream ms = new MemoryStream();
  15:          XmlSerializer xmlSerializer = new XmlSerializer(typeof(Cart));
  16:   
  17:          XmlTextWriter outputXML = new XmlTextWriter(ms, Encoding.UTF8);
  18:          xmlSerializer.Serialize(outputXML, cart);
  19:          outputXML.Flush();
  20:          ms.Seek(0, SeekOrigin.Begin);
  21:   
  22:          byte[] output = ms.ToArray();
  23:          outputXML.Close();
  24:          ms.Close();
  25:   
  26:          Response.ContentType = "application-octetstream";
  27:          Response.Cache.SetCacheability(HttpCacheability.NoCache);
  28:          Response.AppendHeader("Content-Length", output.Length.ToString());
  29:          Response.AppendHeader("Content-Disposition", "attachment; filename=cart.xml; size=" + output.Length);
  30:          Response.AppendHeader("pragma", "no-cache");
  31:          Response.BinaryWrite(output);
  32:          Response.Flush();
  33:      }
  34:      catch (Exception ex)
  35:      {
  36:          Response.Clear();
  37:          Response.ContentType = "text/html";
  38:          Response.Write(ex.ToString());
  39:      }
  40:  }

In the first section through line 10, I retrieve the state object (cart) from Session and make sure it actually exists.  If it doesn't, I'll just send an error message back to the client.

In lines 14 through 24, I create the XmlSerializer to serialize the "cart" variable, and call Serialize to serialize the cart out to the MemoryStream object.  MemoryStream provides an in-memory Stream object that doesn't require you to write to files, etc. for stream actions.  Instead, it basically uses an internal byte array to store stream data.

I could have passed the HttpResponse.OutputStream directly to the XmlTextWriter's constructor, but I would lose the ability to buffer or give size information back to the client, so I just dump it all into a byte array.

Finally, in lines 26 through 32, I set up the Response object appropriately and call BinaryWrite to write the raw byte array out to the client.  I disable caching as I want the client to bypass any server or client cache and always download the latest Cart.  Also, I set the appropriate headers to direct the client to download instead of just view the XML.  If I didn't include the "Content-Disposition" header, most likely the client would simply view the XML in their browser.  That's done through the value "attachment".

I can also control what filename gets created on the client side with the "filename" value in the "Content-Disposition" header.  Without that, a dummy or blank filename would be shown.  Here's what it looks like after I click the "Download cart" button:

Notice that both the filename and file size are populated correctly.  I can save this serialized Cart object anywhere I like now as a perfect snapshot of our state object, ready to be played back.  Also, the "cart.xml" file doesn't exist anywhere on the server.  It only exists in server memory and is streamed directly to the client.

Playing it back

Now that I have a page that allows me to download my Cart from Session, I need a page where I can upload it back up and continue through the application.  This can be accomplished through the FileUpload control and some de-serialization magic.

Uploading the saved state

First, I'll need to add a couple of controls to my "Replay.aspx" page to handle the file upload and to initiate the replay:

<asp:fileupload id="fuCart" runat="server" />
<br />
<asp:button id="btnReplay" onclick="btnReplay_Click" runat="Server" text="Replay" />

In the click handler, I need to read the file from the FileUpload control and deserialize that into a Cart object:

protected void btnReplay_Click(object sender, EventArgs e)
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(Cart));
    Cart cart = (Cart)xmlSerializer.Deserialize(fuCart.PostedFile.InputStream);
    Session["Cart"] = cart;

    Response.Redirect("~/ShoppingCart.aspx");
}

Once the cart is downloaded and deserialized, I set the Session variable to the new cart instance and proceed directly to the ShoppingCart.aspx page.  I can verify that my Cart object has the exact same state as the one I saved earlier by examining it in the debugger:

I can see all of the IDs are correct, the number of items are correct, and all of the data values match the original cart saved out.  When I proceed to the cart page, my state will be exactly where it was when I originally downloaded the cart.

Conclusion

If one of our QA people encountered a defect, they can now save off their state and attach it to our defect tracking system, allowing us to replay exactly what their state was and reproduce the defect.  Record/playback is also perfect for regression test suites, which sometimes need to rely on specific inputs (instead of workflows) to reproduce defects.  Combining this ability with WatiN or Selenium can give me a very powerful testing tool.

When defects are found, we can download the state of the user when replaying their workflow is difficult, impossible, or we just don't know what happened.  Through replaying a user's exact state, we can quickly determine root causes for failures and create regression tests to ensure the defects do not surface again.

Just make sure you take care to secure the "record" and "playback" pages appropriately.  You probably won't want that available to customers.

Friday, August 31, 2007

Legacy code testing techniques: subclass and override non-virtual members

One of the core techniques in Michael Feathers' Working Effectively With Legacy Code is the "Subclass and Override Method" technique.  Basically, in the context of a test, we can subclass a dependency and override behavior on a method or property to nullify or alter its behavior as needed.  This is especially useful if we can't extract a dependency outside of a class under test.  Mocking frameworks such as Rhino.Mocks allow me to verify interactions, or simply put in some canned responses for dependencies.

Since we're dealing with legacy code, paying down the entire technical debt at once isn't an option.  We have to make micro-payments by introducing seams into our codebase.  It might make the code slightly uglier at first, but as Feathers notes in his book, sometimes surgery leaves scars.

Some problem code

I need to override a method to provide an alternate, canned value.  However, in C#, members are not virtual by default.  Members have to be explicitly marked "virtual", otherwise subclassed members can only shadow base members.  For instance, suppose we have class Foo and Bar:

public class Foo : Bar
{
    public decimal CalculateDiscount()
    {
        return CalculateTotal() * 0.1M;
    }
}

public class Bar
{
    public decimal CalculateTotal()
    {
        // Hit database, webservices, etc.
        return PricingDatabase.GetPrice(itemId);
    }
}

I'm trying to test some class that uses Foo.CalculateDiscount method to perform some figure out what shipping methods should be available.  It uses the Foo discount to figure this out.  However, CalculateDiscount calls a base class method (CalculateTotal), which then goes and hits the database!  Not much of a unit test when it hits the database (or web service, or HttpContext, etc.).  Worse, I don't have access to the Bar class, it's in another library that we don't own.  Here's the test I'm trying to write:

[Test]
public void Should_add_shipping_option_when_discount_is_lower_than_50()
{
    MockRepository mocks = new MockRepository();

    Foo foo = mocks.CreateMock<Foo>();

    using (mocks.Record())
    {
        Expect.Call(foo.CalculateTotal()).Return(100.0M);
    }

    using (mocks.Playback())
    {
        string[] shippingMethods = ShippingService.FindShippingMethods(foo);

        Assert.AreEqual(shippingMethods[0], "OneDay");
    }
}

I could try to remove the dependency on the Foo class somehow.  But there's a lot of information that my shipping method needs, so I can't just pass in individual parameters for all of the Foo data.  The Foo class is actually quite large, so trying to extract an interface wouldn't really help either.  In any case, I just want to override the behavior of the "CalculateTotal" call, and since it's not marked "virtual", I can't override the behavior directly.  For example, this won't work in my test:

public class FooStub : Foo
{
    public new decimal CalculateTotal()
    {
        return 100.0m;
    }
}

The shipping service knows about "Foo", not "FooStub".  Since the FooStub.CalculateTotal is shadowing the Bar method, only when I have a variable of type FooStub will its CalculateTotal get called.  Since the shipping service knows Foo, it will use the Bar CalculateTotal method, even if I pass in an instance of a FooStub.  Shadowing can cause weird things like this to happen, to I try to avoid it as much as possible.

Subclass and override

So subclassing and overriding, one of the main functions of mocking frameworks, won't work at the test level.  I need to get the override on or between the Foo and Bar classes.  Why don't we create a new BarSeam class between the Foo and Bar classes?

public class Foo : BarSeam
{
    public decimal CalculateDiscount()
    {
        return CalculateTotal() * 0.1M;
    }
}

public class BarSeam : Bar
{
    public virtual new decimal CalculateTotal()
    {
        return base.CalculateTotal();
    }
}

public class Bar
{
    public decimal CalculateTotal()
    {
        // Hit database, webservices, etc.
        return PricingDatabase.GetPrice(itemId);
    }
}

The BarSeam class now sits between Foo and Bar in the inheritance hierarchy.  BarSeam shadows the Bar.CalculateTotal, with one key addition, the "virtual" keyword.  By making BarSeam.CalculateTotal virtual, I can now subclass Foo and override CalculateTotal, put in a canned response, and not worry about hitting the database.

Yes, BarSeam is ugly, but I want to bring ugly to the front of the class to make sure it doesn't get swept under the rug.  Since all client code either references Foo or Bar, no client code will be affected as BarSeam's default implementation merely calls the base method.  Think of it as Adapter, but instead of incompatible interfaces, I'm dealing with a non-extensible interface.

Conclusion

When working with legacy code, it's not feasible (or even wise) to try and rewrite the application.  By making these micro-refactorings and introducing seams, we're able to identify places in need of larger refactorings, as well as meeting our original goal of getting our legacy code under test.

Wednesday, July 11, 2007

Introducing Behave#

I really like the idea of executable requirements.  Executable requirements is the idea that I can express requirements from the business in a human-readable, executable format.  Part of fulfilling the requirement is that the "executable requirement" part can execute successfully in the form of acceptance tests.

Recently, I checked out a couple of API's for executable requirements in the form of behavior-driven design (BDD).  For more information on BDD, check out these articles from Dan North's blog:

The API's I checked out were NBehave and Joe Ocampo's NUnit.Behave.  NBehave was rather cumbersome to set up, and didn't have much of a fluent interface.  NUnit.Behave was much easier to use, but forced a dependency on NUnit.  I didn't want to be forced to use NUnit, nor did I want to inherit from certain classes or implement certain interfaces.  Heavily influenced by NUnit.Behave, I created Behave#.

What is Behave#?

Behave# (http://www.codeplex.com/BehaveSharp) is a fluent interface to express executable requirements in the form of acceptance tests with a distinct BDD grammar.  Stories follow the "As a <role> I want <feature> so that <benefit>" template.  Stories are made up of scenarios, which follow the "Given When Then" template.  Through a fluent interface, Behave# shapes your acceptance tests to closely match the original user story.

What would a user story look like in code?

 The fluent interface I settled on looks like:

new Story("Transfer to cash account")
    .AsA("savings account holder")
    .IWant("to transfer money from my savings account")
    .SoThat("I can get cash easily from an ATM")

    .WithScenario("Savings account is overdrawn")

        .Given("my savings account balance is", -20)
            .And("my cash account balance is", 10)
        .When("I transfer to cash account", 20)
        .Then("my savings account balance should be", -20)
            .And("my cash account balance should be", 10);

I really like this syntax as it can be read very easily and there aren't a lot of other objects or frameworks getting in the way.  So how do we actually execute custom actions in our story definition?  Here's a full-fledged example, using NUnit to provide assertions:

[Test]
public void Transfer_to_cash_account()
{

    Account savings = null;
    Account cash = null;

    Story transferStory = new Story("Transfer to cash account");

    transferStory
        .AsA("savings account holder")
        .IWant("to transfer money from my savings account")
        .SoThat("I can get cash easily from an ATM");

    transferStory
        .WithScenario("Savings account is in credit")

            .Given("my savings account balance is", 100, delegate(int accountBalance) { savings = new Account(accountBalance); })
                .And("my cash account balance is", 10, delegate(int accountBalance) { cash = new Account(accountBalance); })
            .When("I transfer to cash account", 20, delegate(int transferAmount) { savings.TransferTo(cash, transferAmount); })
            .Then("my savings account balance should be", 80, delegate(int expectedBalance) { Assert.AreEqual(expectedBalance, savings.Balance); })
                .And("my cash account balance should be", 30, delegate(int expectedBalance) { Assert.AreEqual(expectedBalance, cash.Balance); })

            .Given("my savings account balance is", 400)
                .And("my cash account balance is", 100)
            .When("I transfer to cash account", 100)
            .Then("my savings account balance should be", 300)
                .And("my cash account balance should be", 200)

            .Given("my savings account balance is", 500)
                .And("my cash account balance is", 20)
            .When("I transfer to cash account", 30)
            .Then("my savings account balance should be", 470)
                .And("my cash account balance should be", 50);

    transferStory
        .WithScenario("Savings account is overdrawn")

            .Given("my savings account balance is", -20)
                .And("my cash account balance is", 10)
            .When("I transfer to cash account", 20)
            .Then("my savings account balance should be", -20)
                .And("my cash account balance should be", 10);

}

To perform actions with each "Given When Then" fragment, I pass in a delegate (anonymous in this case, but much prettier with lambda expressions in C# 3.0).  This delegate is executed as the story execution proceeds, and is cached by name, so each time the story sees "my cash account balance is", it will execute the appropriate delegate.  I don't need to define the custom action every time.

The result of the execution is the story results outputted in a human readable format (by default, to Debug):

Story: Transfer to cash account

Narrative:
   As a savings account holder
   I want to transfer money from my savings account
   So that I can get cash easily from an ATM

   Scenario 1: Savings account is in credit
      Given my savings account balance is: 100
         And my cash account balance is: 10
      When I transfer to cash account: 20
      Then my savings account balance should be: 80
         And my cash account balance should be: 30

      Given my savings account balance is: 400
         And my cash account balance is: 100
      When I transfer to cash account: 100
      Then my savings account balance should be: 300
         And my cash account balance should be: 200

      Given my savings account balance is: 500
         And my cash account balance is: 20
      When I transfer to cash account: 30
      Then my savings account balance should be: 470
         And my cash account balance should be: 50

   Scenario 2: Savings account is overdrawn
      Given my savings account balance is: -20
         And my cash account balance is: 10
      When I transfer to cash account: 20
      Then my savings account balance should be: -20
         And my cash account balance should be: 10

This format closely resembles the original user story I received from the business.

Conclusion

I like being able to verify deliverables in the form of automated tests.  When these tests closely resemble the original requirements as user stories, I'm more confident in the deliverables.  Having executable requirements in the form of acceptance tests in a fluent interface that matches the original requirements can bridge the gap between what the business asks for and what gets delivered.  Behave# gets us one step closer to bridging that gap.

Wednesday, May 23, 2007

Unit testing with stubs and Rhino Mocks

I've been using Rhino Mocks for about a year now, and Oren has never failed to impress me with the features he keeps adding on a regular basis.  I needed to test a particular method that accepted an IProfile interface as an argument.  I didn't want to use an existing IProfile implementation I found, I was really interested in just sending the method a stub.  If I used Rhino Mocks to create a mock, I'd have to set a bunch of expectations to get everything set up, but I really just want a stub.  It's a huge pain to set up a stub manually right now, as this would entail creating your own class that implemented IProfile with a basic implementation, etc.  For more information about mocks, stubs, dummy objects and fake objects, check out Fowler's paper on the subject.  Here's the test I created:

[TestMethod]
public void SetPaymentType_WithValidPayment_AddsPaymentFieldToPaymentFields()
{
    MockRepository repo = new MockRepository();
    IProfile profile = repo.Stub<IProfile>();
    IPayment payment = repo.Stub<IPayment>();

    using (repo.Record())
    {
        profile.Payments = new IPayment[] {payment};
        payment.PaymentCode = "CC";
    }

    using (repo.Playback())
    {
        bool result = ProfileHelper.SetPaymentType("TestValue", profile);

        Assert.AreEqual(true, result);
        Assert.AreEqual(1, payment.PaymentFields.Length);

        IField paymentField = payment.PaymentFields[0];

        Assert.AreEqual("PaymentType", paymentField.FieldKey);
        Assert.AreEqual("TestValue", paymentField.FieldValue);
    }
}

The MockRepository object is from Rhino Mocks.  I call the Stub method to generate a stub object for the interfaces I'm interested in, which are specifically the IProfile and IPayment types.  I set the MockRepository to Record to put in the initial values for my stubs.  Note that Rhino Mocks creates the interface types, and nowhere in my code will I create an implementation of IProfile or IPayment.  Rhino Mocks does this for me.  I set the MockRepository back to Playback mode and call the method I wanted to test (ProfileHelper.SetPaymentType).  Notice that the SetPaymentType method modifies the PaymentFields property on the IProfile object, and does it correctly.  I finish out the test making assertions about the values that should be set in the IProfile object.

What's clear from looking at this test is that I'm only concerned about testing the interaction between the ProfileHelper.SetPaymentType method and the IProfile object, but I don't care about the specific implementation of the IProfile object.  If I passed in a specific implementation of an IProfile object, there may be some unwanted side effects that might cause some false positives or false negatives.  Using stubs makes sure I limit the scope of what's being tested only to the method I'm calling.

Monday, April 23, 2007

Classifying tests

When defining a testing strategy, it's important to take a step back and look at what kinds of tests we would like to develop. Each type of test has a different scope and purpose, and can be developed by different roles in an organization. Most kinds of testing are concerned with verification and validation, also known as "V&V". Verification deals with lower level, "am I building the software right" kinds of tests. This usually entails some form of unit testing. Validation answers the question "am I building the right software", which focuses on higher level or business related tests. I've usually seen tests broken down into the following categories:

  • Unit tests
  • Integration tests
  • Functional tests

I've ignored regression and performance tests, because both of these tests take the form of any of the above test types. These test definitions come more from the agile school of testing.

Unit tests

So you just wrote a piece of code to implement some feature. Does it work? Can you prove it? If I come back tomorrow, can you prove it again? What about next week, or next month, or next year? If another developer modifies your code, can they prove it still works, and didn't break your functionality?

Unit testing answers the first two questions. Namely, does my code do what I think it's supposed to do? Continuous Integration will answer the rest.

Scope

The scope of a unit test is a single unit, usually a single public member. Unit tests should only test that unit, with no interaction with external dependencies. Unit tests can be defined as:

  • Isolated from external dependencies
  • Repeatable
  • Testing only one thing
  • Easily readable
  • Order independent
  • Side effect free
  • Having only one reason to fail
  • Written by the developer
  • Fast to run

If a unit test hits the database, then it's no longer a unit test because it depends on an external module. If the database goes down, I'm not testing the unit anymore, I'm testing to see if the database is up. Other external dependencies include:

  • Databases
  • HttpContext items (Querystring, session, etc.)
  • Web services
  • File I/O
  • Anything else that accesses the network or the disk

If I can remove external dependencies of a class during unit testing, I can greatly reduce the number of reasons for a unit test to fail. Ideally, my tests are also automated so they can be easily run. On my last project, we started writing unit tests on all new development, and regression tests on existing behavior. We wound up with over 1200 unit tests in about six months for about 30K lines of code, covering nearly 100% of new code (~98%) and about 50-75% of the existing codebase. It's also typical to see a 1:1 or 1.5:1 ratio of unit test code to production code in a team practicing TDD.

Purpose

Unit tests should test only one thing and have only one reason to fail. In a future post, I'll dive more into unit testing with examples. Since programmers are human and make mistakes on a daily basis, unit tests are a developer's back up to verify small, incremental and individual pieces of functionality are implemented the way the developer intended. Unit tests strive to answer the question "does my code do what I think it's supposed to do?"

Integration tests

I've written a suite of unit tests that verify the functionality I was trying to create. I've abstracted external dependencies away so I can make sure that my tests have only one reason to fail. But in production, the web service does exist. The database is there. Emails are sent out, queue messages sent, files created and read. Integration tests put the different pieces together to test on a macro scale. Integration tests can be defined as:

  • Tests for dependencies between objects and external resources
  • Repeatable
  • Order independent
  • Written by an independent source (QA)

In other words, integration tests are more end-to-end to determine if the entire system is functioning correctly.

Scope

As you can see, integration tests are more on the "macro" scope of testing. These tests can be written in a unit testing framework, but are also written in other frameworks such as FIT or WATIR. These are the tests to make sure that the database is written to correctly, that an email was sent, and a MSMQ message was written correctly.

Purpose

In the real world, we have external dependencies and we should test them. Integration tests verify that the code functions correctly in the presence of these external dependencies. We can test if a single module works with the external dependencies present, or if a group of modules works together correctly. Either way, integration tests are about putting the pieces together and determining if they fit.

Functional tests

We've developed some software and have tests that isolate dependencies and embrace them. But we're still not guaranteed that we've written the software that business has demanded. Having unit and integration tests is fine and dandy, but if our software doesn't meet business requirements, it's just been a huge waste of time and money. Functional tests are:

  • Developed by, or with the direct assistance of, the business owners
  • Focused on verifying business requirements
  • Written in a very high-level language such as a DSL

Scope

Functional tests are as end-to-end as tests come. These tests are performed on the topmost layers of an n-tier architecture, as these are the layers seen by the business or the customers. These tests are often the slowest, and can be a mix of automated and manual testing. These tests can also be used to sign off on project completion.

Purpose

Business has a set of requirements the software must meet, and functional tests are the way of verifying our software meets those requirements. Since requirements come in may forms, functional tests can be any kind of tests to verify those requirements, from "Does the website look good" to "When I check out, is the terms and conditions displayed".

Looking back, looking forward

I'm sure there are more types of testing we could look at, including user acceptance or user interface testing. These testing types go outside the scope of verification and validation, so I left them out of this post.

Automating your tests will give you insight to information such as code coverage and other code metrics, especially if they are part of a nightly or continuous integration build. As the scope of tests grows from unit to functional, and the number of bugs discovered should decrease as well. It's much easier to fix a bug in a unit test than in a functional test because of the scope of each type. If I have fewer places to look, I've cut the time to find and fix the bug dramatically. Since it isn't enough just to deliver functionality to the business, but to also create a clean and maintainable codebase, a solid suite of tests is absolutely critical for enabling changes for future business requirements. And if they were automated, that would be really cool too :).