exception expectation

In my last post I created a new BalancePresenter class with a constructor requiring two parameters: IBalanceView and IRepository.
(Catch up on this series of posts: one, two, three)

Now I want to ensure that at the point of entry I can identify if either of these parameters are null. In the absence of Code Contracts I'll have to roll my own code.
First I write the tests and here I come across a bone of contention for many when dealing with exceptions - what should the observation name be?

My context is "when_creating_a_balance_presenter" which is very clear, but the observation name could be either "should_throw_an_argument_null_exception_if_balance_view_is_null" or a more generic "should_fail_if_balance_view_is_null".

In my previous projects using traditional unit testing I have used the first - being very explicit about what the observation is testing, but this exposes the internal implementation.
Do we really need to describe the exception type we expect when this is already self-described by the test code within the observation? I've recently had a change of heart and now want my observations to be descriptive and accurate but not exhaustive - they should not deal with implementation details.

Here is how I first wrote the observation code (and please note that I normally red/green/refactor one observation at a time but to save space on this post I've done two at once below).

[Observations] 
public class when_incorrectly_creating_a_balance_presenter : BalancePresenterSpecification 
{ 
    private static IBalanceView balanceView; 
    private Exception exceptionCaughtWhileCreatingThePresenter; 

    private context c = () => balanceView = an<IBalanceView>(); 

    [Observation] 
    public void should_fail_if_balance_view_is_null() 
    { 
        try 
        { 
            BalancePresenter invalidPresenter = new BalancePresenter(null, 
                          new MemoryRepository()); 
        } 
        catch (Exception ex) 
        { 
            exceptionCaughtWhileCreatingThePresenter = ex; 
        } 

        Assert.IsInstanceOfType(typeof(ArgumentNullException),
                      exceptionCaughtWhileCreatingThePresenter); 
    } 

    [Observation] 
    public void should_fail_if_repository_is_null() 
    { 
        try 
        { 
            BalancePresenter invalidPresenter = new BalancePresenter(balanceView, null); 
        } 
        catch (Exception ex) 
        { 
            exceptionCaughtWhileCreatingThePresenter = ex; 
        } 

        Assert.IsInstanceOfType(typeof(ArgumentNullException), 
                      exceptionCaughtWhileCreatingThePresenter); 
    } 
} 

I then easily saw the repeated code pattern and refactored this:

[Observations] 
    public class when_incorrectly_creating_a_balance_presenter : BalancePresenterSpecification 
    { 
        private static IBalanceView balanceView; 

    private context c = () => balanceView = an<IBalanceView>(); 

        [Observation] 
        public void should_fail_if_balance_view_is_null() 
        { 
            AssertThatWeCatchAnArgumentNullExceptionWhenCreatingAPresenterWith(null,
                                 new MemoryRepository()); 
        } 

        [Observation] 
        public void should_fail_if_repository_is_null() 
        { 
            AssertThatWeCatchAnArgumentNullExceptionWhenCreatingAPresenterWith(balanceView, 
                                 null); 
        } 

        private void AssertThatWeCatchAnArgumentNullExceptionWhenCreatingAPresenterWith(
                                 IBalanceView view, IRepository repository) 
        { 
                  Exception exceptionCaughtWhileCreatingThePresenter;  

            try 
            { 
                BalancePresenter invalidPresenter = new BalancePresenter(view, repository); 
            } 
            catch (Exception ex) 
            { 
                exceptionCaughtWhileCreatingThePresenter = ex; 
            } 

            Assert.IsInstanceOfType(typeof(ArgumentNullException), 
                                 exceptionCaughtWhileCreatingThePresenter); 
        } 
}

This looks much better than the first attempt but there are a few things wrong with this that I didn't like. So digging into the bdd library innards I came up with the following much better syntax which I will illustrate further in a moment. But first, the implementation needs putting in (again, one test passing at a time, but here, the code is shown once):

public BalancePresenter(IBalanceView balanceView, IRepository repository) 
{ 
    if(balanceView==null || repository==null) 
        throw new ArgumentNullException(); 

    this.balanceView = balanceView; 
    this.repository = repository; 
}

I have a better way of checking for null arguments that I aim to present in a future post, but for the purpose of this illustration the above code will suffice.

Onto the better test syntax... again, after looking at the code on the base classes of the bdd library I cleaned my test code into the following:

[Observations] 
public class when_incorrectly_creating_a_balance_presenter : BalancePresenterSpecification 
{ 
    private static IBalanceView balanceView; 

    private context c = () => balanceView = an<IBalanceView>(); 

    private static BalancePresenter invalidBalancePresenter; 

    [Observation] 
    public void should_fail_if_balance_view_is_null() 
    { 
        doing( () => invalidBalancePresenter = new BalancePresenter(null, 
                                 new MemoryRepository()) ); 
        exception_thrown_by_the_sut.should_be_an_instance_of<ArgumentNullException>(); 
    } 

    [Observation] 
    public void should_fail_if_repository_is_null() 
    { 
        doing( () => invalidBalancePresenter = new BalancePresenter(balanceView, null) ); 
        exception_thrown_by_the_sut.should_be_an_instance_of<ArgumentNullException>(); 
    } 
}

Here I am still setting the same context up where a mock is generated for my IBalanceView instance but I no longer need to catch the exception myself. A public property on the base class in the bdd library called "exception_thrown_by_the_sut" exposes any exception that occurred when processing the an Action called "behaviour_performed_in_because":

static public Exception exception_thrown_by_the_sut 
{ 
    get { return exception_thrown_while_the_sut_performed_its_work ?? 
              (exception_thrown_while_the_sut_performed_its_work = 
                 get_exception_throw_by(behaviour_performed_in_because)); } 
} 

static Exception get_exception_throw_by(Action because_behaviour) 
{ 
    try 
    { 
        because_behaviour(); 
        return null; 
    } 
    catch (Exception e) 
    { 
        return e; 
    } 
} 

static public void doing(Action because_behaviour) 
{ 
    behaviour_performed_in_because = because_behaviour; 
}

The code above is from the bdd library and note that the doing() method stores the action that is sent in on the "behaviour_performed_in_because" member.

Therefore within my observation I can set the action using the doing() method and then assert that an exception is raised when the action is performed.
I'm also using better assertion syntax from the bdd library with the extension method "should_be_an_instance_of<T>()".

Posted at at 10:30 PM on Wednesday, April 29, 2009 by Posted by Justin Davies | 5 comments Links to this post   | Filed under: ,

behaviour specifications

In the last few posts I've been exploring the use of a context specification style library for writing tests. This post continues on that vein with the user story I visited last time:

"As a user I want to view the current balance so that I can see the amount and date that it was captured."

I got as far as the first set of observations for a Balance class - a value object to hold the concept of a current balance. In order for me to deliver this story out to the UI I need a way to retrieve this data so the next step is a repository.
I create a new class called MemoryRepositorySpecification that will hold all the data access code for the time being (I can put a real implementation in later) and begin with the specification:

public class MemoryRepositorySpecification : 
    observations_for_a_sut_with_a_contract<IBalanceRepository, MemoryRepository> 
{ }

This time I'm using a different base class that enforces a contract - although I am testing MemoryRepository as my SUT, I can only test members that exist on the contract interface IBalanceRepository.

[Observations] 
public class when_a_current_balance_is_required : MemoryRepositorySpecification 
{ 
    [Observation] 
    public void should_be_able_to_provide_current_balance_from_the_memory_repository() 
    { 
       sut.GetCurrentBalance().should_not_be_null(); 
    } 
}

This is a very primitive test and simply asserts that a Balance instance does come back from the GetCurrentBalance() method I have just defined in my test.
When I put placeholder code in for this for compile, returning null the test fails so I then implement this by returning a Balance instance:

public interface IBalanceRepository 
{ 
    Balance GetCurrentBalance(); 
} 

public class MemoryRepository : IBalanceRepository 
{ 
    public Balance GetCurrentBalance() 
    { 
        return new Balance(10.5, DateTime.Now); 
    } 
}

I now have a basic repository implementation and a Balance class - this is purposefully as basic as possible but is still written as production code until I later swap out the data access object.
I now need to define my presenter and view for display in the UI where a webform page will implement the view.

I start with a new folder in my Plutus.Core project "Presenters" and add the "BalancePresenterSpecification" class in here. This will define my presenter and the logic I want to begin with is that during an Initialise call to the presenter, the current balance will be obtained. Being dogmatic, this is actually an assumption on the user story (that the current balance needs to be obtained when the view/page loads/initialises) but suits my purposes for this exercise.
My first step is the specification class, declaring the SUT as a new BalancePresenter class:

public class BalancePresenterSpecification : 
   observations_for_a_sut_without_a_contract<BalancePresenter> 
{  }

I then write my observation:

[Observations] 
public class when_creating_a_balance_presenter : BalancePresenterSpecification 
{ 
    private static IBalanceView mockBalanceView; 

    private context c = () => 
                            { 
                                MockRepository mockRepository = new MockRepository(); 
                                mockBalanceView = mockRepository.DynamicMock<IBalanceView>();  
                                // note that these lines above change later in the post 
                            }; 

    [Observation] 
    public void should_be_able_to_provide_a_balance_view_and_a_balance_repository() 
    {            
        BalancePresenter balancePresenter = new BalancePresenter(mockBalanceView, 
                                                  new MemoryRepository()); 
    } 
}

Here I am setting up a context for my observation using one of the "Arrange" parts of the context specification library - the static context delegate. This is a delegate simply declared as follows:

namespace developwithpassion.bdd.contexts 
{ 
    public delegate void context(); 
}

During the test run the context is run before the SUT is set up and all contexts are identified and run (if you had one on base class and on sub class for example). In my context I am using a lambda expression to declare an anonymous method that creates a mock object implementing a new IBalanceView interface - I use a mock object rather than a stub (that I would manually create) so that I need not concern myself with future changes on that interface... the mock will take care of it on my behalf.

All that is needed now is to create IBalanceView interface (and move it to a "Views" folder) and create the constructor for the BalancePresenter, both really easy with a few Resharper key-strokes:

namespace Plutus.Core.Views 
{ 
    public interface IBalanceView 
    { 
    } 
}

public class BalancePresenter 
{ 
    private IBalanceView balanceView; 
    private IBalanceRepository balanceRepository; 

    public BalancePresenter(IBalanceView balanceView, IBalanceRepository balanceRepository) 
    { 
        this.balanceView = balanceView; 
        this.balanceRepository = balanceRepository; 
    } 
}

Note that I've jumped straight into implementing this code rather than red-green-refactor process as it is fairly straightforward and easier to illustrate on a blog post.

Now for some clean up and some better syntax - I've put my initial version of code that I wrote using traditional Rhino Mocks code to mock out the IBalanceView interface and provide a proxy.
Here is a better way of doing so using the bdd library:

[Observations] 
public class when_creating_a_balance_presenter : BalancePresenterSpecification 
{ 
    private static IBalanceView balanceView; 

    private context c = () => balanceView = an<IBalanceView>(); 

    [Observation] 
    public void should_be_able_to_provide_a_balance_view_and_a_balance_repository() 
    {            
        BalancePresenter balancePresenter = new BalancePresenter(balanceView, 
                                                new MemoryRepository()); 
    } 
}

I've removed the need for a MockRepository instance by using the "an()" method on the base observation class. This wraps generating a stub using the static method in RhinoMocks:

static public InterfaceType an<InterfaceType>() where InterfaceType : class 
{ 
    return MockRepository.GenerateStub<InterfaceType>(); 
}

It is an excellent naming convention for mocking interfaces that begin with an "I" and reads well. Note that in this new version I don't feel obligated to call is "mockBalanceView" anymore as I'm not directly interacting with the mock repository (you could argue that I was never obligated! But this expressive syntax definitely cleans the code up in my experience).

Also of note is that I've also customised the library at a later date to provide a mock version:

static public InterfaceType aMockOf<InterfaceType>() where InterfaceType : class 
{ 
    return MockRepository.GenerateMock<InterfaceType>(); 
}

Now I'm about to invalidate the main code in this post by saying that all of this it isn't actually required.

The contract on the constructor is already handled by the code wiring up the sut behind the scenes - I need never therefore put this type of code in. However I want to clearly express what the dependencies are in my test output and therefore have this "should be able to provide a balance view and a balance repository" specification available.
It also helped me test drive the code using Resharper and does no harm in sitting there, save the possibility of review when the constructor changes.. but again I would test drive from this specification.
It also leads very well into the next blog post I will be writing on exception expectations so remains part of my test suite at present.

Perhaps when I'm much more comfortable with behaviour driven development I'll only have real behaviours as my specifications and not contract ones already enforced by the compiler.

Posted at at 10:40 PM on Monday, April 27, 2009 by Posted by Justin Davies | 0 comments Links to this post   | Filed under: ,

first steps into context specification

In my previous post I outlined what I want to blog about over coming posts and how I will model an application using behaviour driven design.
So let's get to it.

First I create a new C# class library project called Plutus.Core. This will hold the domain objects, the presenters and views and will have the specifications right alongside the classes that they test (I don't see any need at this stage to have a separate test assembly).
I add the developwithpassion.bdd library to the solution and reference that from my core project. I also reference MbUnit.Framework.dll and the Rhino.Mocks.dll assemblies.

I'm now ready to begin writing code to support my user stories - I have a list of user stories that I want covered by my application, but in these posts I'll pick them off one at a time.
Here's the first:

"As a user I want to view the current balance so that I can see the amount and date that it was captured."

This story suggests that I need a domain entity to hold a balance and for this to have a date and amount property. At this stage there is no logic for me to write so I will make this a data value object that will be readonly after instantiation.

I create a class to hold the specifications for our new code I will be writing and call it "BalanceSpecification" - the file sits within a "Domain" folder within the Core project.

My first crack at the code is as follows:

using System; 
using developwithpassion.bdd.mbunit; 
using developwithpassion.bdd.mbunit.standard; 
using developwithpassion.bdd.mbunit.standard.observations;

namespace Plutus.Core.Domain 
{ 
    public class BalanceSpecification : observations_for_a_sut_without_a_contract<Balance> 
    { 
        protected static double amount = 1234.50; 
        protected static DateTime date = DateTime.Now; 

        public override Balance create_sut() 
        { 
            return new Balance(amount, date); 
        } 
    } 
}

The BalanceSpecification class will act as a base class for all the "Observations" that I want to make on the domain code that I will be writing. Notice that it inherits from "observations_for_a_sut_without_a_contract" class - this is part of the developwithpassion library and facilitates the wiring up of our tests into the context specification style and AAA pattern of testing.
Under the hood it hooks up the system-under-test (SUT) for me based on the T type declaration - in this case a Balance class.

I am overriding the "create_sut()" method to provide my own implementation of the system under test for use in my observations.
For this code to build I obviously have to create an empty shell Balance class - using Resharper I can easily create the class within the same file with a few keystrokes and work with both classes side by side for the time being. I find this the fastest way of making changes in my code as my observations grow until I decide it is time to pull the Balance class out into its real location - a Balance.cs file.

Now I am ready to make my first observation:

[Observations] 
public class when_a_new_balance_is_created : BalanceSpecification 
{ 
    [Observation] 
    public void should_contain_the_amount_it_was_created_with() 
    { 
       sut.Amount.should_be_equal_to(amount); 
    }
}

The class is decorated with an "ObservationsAttribute" - this is again part of the testing library and inherits from MbUnit TestFixturePatternAttribute. The class name is purposefully expressive with underscores within the name and provides a context for the observations I am making... "when a new balance is created (we want to observe that it conforms to specification)".
The test itself is decorated with "ObservationAttribute" and this is also purposefully expressive in its name - "should conform to specification". Put together they express our intent in a very readable way - "when a new balance is created it should contain the amount it was created with".

The code itself uses a static public member of the base test class called "sut" (system under test). This is of type T obtained from the type declaration in observations_for_a_sut_without_a_contract. In this case the sut member is of type "Balance".
This is perhaps the least expressive part of the test syntax under this library - to an untrained eye "sut" doesn't really mean anything, however after a brief introduction - "it means the system under test, the type that is declared in the specification's class declaration" I think we can live with it and its easily understood. To be frank I haven't been able to think of anything more rewarding that provides more clarity other than a verbose member name like systemUnderTest which is just too long as a prefix to our assertions. So sut it is.

My assertion is made using an extension method that makes the code, again, very readable - "the system under test's Amount should be equal to amount". Compare that to the following non-intuitive standard assertion syntax:

Assert.AreEqual(amount, sut.Amount);

Under the hood this extension method basically wraps the MbUnit assert:

static public void should_be_equal_to<T>(this T actual, T expected) 
{ 
    Assert.AreEqual(expected, actual); 
}

So I have my first observation, it is written with a context in mind, is very readable and is written in the AAA style. Because the behaviour under test is constructor driven I don't really have an "Act" - I only have "Arrange"(in the base class in create_sut) and "Assert" (in my individual observations). In later posts I will hopefully illustrate some more complex arrange and act code, but for now this suits my purpose.

I now fix the compile errors produced by the missing Amount property and have a placeholder implementation of the Balance class as follows:

public class Balance 
{ 
    public Balance(double amount, DateTime date)  { } 

    public double Amount { get { return -1} } 
}

I'm now ready to run the test and because I have Resharper I can use the test runner. I've installed an MBunit plug in for resharper so that it can pick up the [Observations] and [Observation] attributes in the resharper test runner.

I have also mapped a keyboard shortcut to automatically run in the current context - I've mapped this to Alt-T keystrokes and with my cursor in the observation class I hit Alt-T and my test runs in the reshaper runner.
Predictably and correctly the test fails and I now need to implement the code:

public class Balance 
{ 
    private readonly double _amount;

    public Balance(double amount, DateTime date) 
    { 
        _amount = amount; 
    } 

    public double Amount { get { return _amount;} } 
}

When I run the tests again they pass and I can move onto my second observation:

[Observations] 
public class when_a_new_balance_is_created : BalanceSpecification 
{ 
    [Observation] 
    public void should_contain_the_amount_it_was_created_with() 
    { 
        sut.Amount.should_be_equal_to(amount); 
    } 

    [Observation] 
    public void should_contain_the_date_it_was_created_with() 
    { 
        sut.Date.should_be_equal_to(date); 
    } 
}

Again, I put a placeholder in for the date property to enable me to run the test, see it fail and then implement the real code:

public class Balance 
{ 
    private readonly double _amount; 
    private readonly DateTime _date; 

    public Balance(double amount, DateTime date) 
    { 
        _amount = amount; 
        _date = date; 
    } 

    public double Amount { get { return _amount;} } 
    public DateTime Date { get { return _date; } } 
}

The tests pass and I have now completed my first specification with a couple of observations.

In the next few post I will dig deeper into the story and attempt to deliver the functionality in more detail..

Posted at at 11:02 PM on Monday, April 20, 2009 by Posted by Justin Davies | 0 comments Links to this post   | Filed under: ,

experiments in context specification

In my spare time I've been working with new ways of writing tests at all levels such as unit, integration and acceptance, and one thing remains constant in all these experiments - the need to have the tests be expressive so that they easily communicate their intent and have them as readable as possible to an alien eye, be it another developer, a tester or a business analyst or product owner.

The traditional style of unit testing has a certain way of forcing us to think in intricate implementation detail and this is expressed very well by Scott Bellware on his podcast with the Herding Code guys.

Over the next few posts I'm hopefully going to try and illustrate my current way of writing tests using a context specification style that allows the tests to be more behaviour driven and encourages the developer to think differently about both the test and how the code they are writing will be consumed.
This is by no means a definitive statement of how beahviour driven testing should be but more my journey into a better way of doing things.

I've decided to create an example project that deals with personal finance management - it is not meant to be a thorough application by any means, but will hopefully provide some rich behaviours that I will need to model. More importantly I'm sure there will be many different contexts that will crop up and allow me to see the fruit of the context specification style in action.
Rather than present the finished article when illustrating the code I will aim to show the progress of the code in all forms of good, bad and the ugly.

The library I'm using to develop my tests is the developwithpassion.bdd library from Jean-Paul Boodhoo.

This project forms an expressive wrapper on top of mbunit that turns the library into a context driven one with Act-Arrange-Assert style syntax. It also wraps Rhino Mocks with extension methods to make them more expressive. Where possible I will try and communicate where the library is helping us be expressive, but this will not be an exhaustive explanation of the library, for that please see Jean-Paul's blog.

The application will be written using the Model-View-Presenter pattern and I had two common patterns to choose from; the passive view and the supervising controller.

My personal style is not to have intermediate DTO objects in between the presenter and the view that provides context data between the two, so I will generally be going with the passive view.

There is also the communication mechanism to think about between the view and presenter - we can use events to communicate to the presenter when something happens on the view, or we can communicate directly from the view using presenter methods.

Again, my personal style is to favour the direct communication without the ugly event syntax, but there may be room for hooking up to the existing web forms Init and Load events of the page life cycle automatically so we can remove the need for an Init or Start() method on the presenter that always has to be called. Alternatively I may create a base presenter and view class that handles the initialisation process without a need for it in every concrete view.

Enough preamble, I'm off to write the code.

Posted at at 10:21 AM on Sunday, April 19, 2009 by Posted by Justin Davies | 0 comments Links to this post   | Filed under: