An Observation about TDD

To me, developers that are not applying TDD practices during their day-to-day job always seem more in a hurry than developers that do apply red-green-refactor. In their hurry, they’re the first to cut corners and start making messes while they rush to their goal. A while ago it dawned to me why that is. They subconsciously want to get feedback as soon as possible about the code they’re writing. They cut corners and generally mess up their code in order to prevent spending those extra hours and days to keep things clean. Constantly refactoring and cleaning up their code is restraining them from having the feedback they so desperately want.

Humans are in fact feedback junkies. We constantly want to know how we’re doing what we’re doing. I actually wrote a blog post about this a couple of years ago.

Since I adopted TDD as a discipline, I tend to feel less pressured which results in me taking the time to continuously refactor the code I’m working on, trying to keep everything clean. Why? Because I known that the code I wrote a minute ago works. The tests I write constantly give me a shot of feedback so that I’m constantly hooked.

Just an observation …

AutoTest.NET

I just want to quickly point out a tool that I’ve been playing with for a couple of days now, named AutoTest.NET. Its an open-source tool that originates from a popular tool in the Ruby community called ZenTest, which basically runs all your valuable unit tests when you save your source files or when you build your code. It enables you to get feedback about your changes as soon as possible.

The project started out a couple of years ago on Google code and was first initiated by James Avery. Contribution stopped at some point until recently where Svein Arne Ackenhausen forked the source code and put it on GitHub. Now it runs both for .NET as well as Mono, with NUnit, MSTest and xUnit as the currently supported unit test frameworks.

Here’s a screenshot from the feedback window when all tests pass:

Success

And here you can see the same window after I broke one of my unit tests:

Failure

Here you can see which particular unit test has been broken and by clicking the specified link you end up at the right source file in Visual Studio.

I encourage you to pick up this small tool and learn how it can facilitate your TDD flow. Take a look at this page in order to get up-and-running in no time. Also don’t forget to provide the owner(s) of this project with some feedback that you might have. Svein has been very helpful over the last week answering all my stupid questions and remarks (and the Nobel price for this year’s most patient person goes to … 😉 ).

I would definitely like to see this tool becoming more popular, so go check it out.  

Boxcar Case Macro in Visual Studio 2010 – Video

I get so much use out of this handy dandy little macro that I just had to share it. It is a simple little Visual Studio macro that should work in 2010 or 2008 to change a string like this:

“When writing a unit test”

into this:

When_writing_a_unit_test

And do it in a single keystroke. My dirty little secret? I am a bad typist, so I need little helpers like this.

The following video will walk you through installing the macro and binding it up to a keyboard shortcut. If you haven’t worked with Visual Studio macros before, this might help get there a bit faster.

image

MP4

 

And here is the macro itself.

Imports System

Imports EnvDTE

Imports EnvDTE80

Imports EnvDTE90

Imports EnvDTE90a

Imports EnvDTE100

Imports System.Diagnostics

Imports System.Windows.Forms

Imports System.Text.RegularExpressions

 

Public Module BddMethods

 

    Sub BoxcarTheCurrentLineOfCode()

 

        Dim description As String

        Dim regEx As Regex = New Regex("""([^""]+)""")

 

        If DTE.ActiveDocument Is Nothing Then Return

 

        Dim currentLine As TextSelection = GetCurrentLine()

        If (currentLine Is Nothing Or currentLine.Text.Length() < 1) Then Return

 

        Dim stringMatch As Match = regEx.Match(currentLine.Text)

        For Each stringMatch In regEx.Matches(currentLine.Text)

            currentLine.Text = currentLine.Text.Replace(stringMatch.Value, BoxcarAString(stringMatch.Value))

        Next

 

        currentLine.EndOfLine()

    End Sub

 

    Private Function BoxcarAString(ByVal textSegmentToChange As String) As String

 

        Dim segmentAfterTheChange As String = textSegmentToChange.Trim()

        segmentAfterTheChange = segmentAfterTheChange.Replace("""", "")

        segmentAfterTheChange = segmentAfterTheChange.Replace(" ", "_")

 

        Return segmentAfterTheChange

 

    End Function

 

    Private Function GetCurrentLine() As TextSelection

 

        Dim currentLine As TextSelection = DTE.ActiveDocument.Selection()

        currentLine.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstColumn)

        currentLine.EndOfLine(True)

 

        Return currentLine

 

    End Function

 

End Module

 

An Evolution of Test-Specification Styles – My Journey to MSpec

Over the last few years, the practice of Test-Driven Design and Behavior-Driven Design has increased in acceptance, even if its practice has not increased in equal proportion.  From my perspective, specification-based design is a natural way to develop software.  Each developer has a preferred framework, and a framework they loathe.  In the .NET world, there are a plethora of unit testing frameworks – NUnit has been nearly ubiquitous; mbUnit was evolutionary; xUnit was revolutionary; MSTest is…er, getting an update.  For BDD, you can find frameworks like SpecUnit.NET, NBehave, and MSpec.  My current framework of choice is MSpec, especially when coupled with StructureMap’s automocking container and a couple helper classes.

From my unscientific observation, developers either love or hate MSpec.  For those that hate MSpec, I wonder if it is the grammatical syntax or the lambda-expression style creating the aversion.  Some even expound MSpec as cryptic and cumbersome.  This seems to be a common complaint – one I hope to address in this post.

I find that those drawn to MSpec have experienced an evolution of testing/specification styles, influenced partially by the community and partially by frameworks they have used.  At the very least, this has been my experience as I have transitioned from xUnit frameworks.

Conventions of MSpec

I particularly like the conventions MSpec encourages using its four delegate types:

Establish:

  • Provides setup (context) for the specification
  • One per class (but not required)
  • “Unlimited” per specification or inheritance chain
  • Runs down the inheritance chain prior to the Because delegate

Because:

  • The action/event being tested
  • One per specification

It:

  • An assertion (usually extension methods/fluent interfaces based on NUnit/xUnit Assert classes)
  • “Unlimited” per specification/class
  • Can be “hosted” in a Behavior class
  • Runs after the Because
  • Can be reused when placed in a Behavior class
  • If body of delegate is missing, will mark as “Ignored” or “Not Implemented” in a test runner

Cleanup:

  • Provides teardown for the specification
  • One per class (but not required)
  • “Unlimited” per specification or inheritance chain
  • Runs up the inheritance chain after the It delegates are completed

MSpec also has one other delegate type (Behaves_like<T>) and several optional attributes available (Subject, Tag, Ignore, Behavior).  [Subject] provides additional information about the specification. [Tag] is similar to the [Category] attribute in NUnit.  [Ignore] is self-explanatory. [Behavior] marks a class made up entirely of assertions (It delegates).  Behaves_like<T> is a delegate type that can be included in a specification block taking the place of a set of assertions (It delegates).

 

NUnit – TestFixture-Per-Class

I have gone from using a TestFixture-Per-Class style to a behavior-driven/context-specification style.  I would like to use the standard HomeController, created in an ASP.NET MVC 1.0 project, as an example class to explore this evolution. 

In my TestFixture-Per-Class days, I may have tested the Index action as follows:

[TestFixture]
public class HomeControllerTests
{
    [Test]
    public void IndexActionTest()
    {
        var controller = new HomeController();
        var result = (ViewResult) controller.Index();
        Assert.AreEqual("Welcome to ASP.NET MVC!", result.ViewData["Message"]);
    }
}

I do like the simplicity of the code.  One line to set up the test, one to execute, and one to assert.  There is a little ceremony involved with marking the class and methods with the NUnit attributes.  With this simple test, it is easy to distinguish the setup code from the assertion; yet, a more complex test would make scanning the test more difficult.  Comments can help, but tend to just add noise.

 

NUnit – Arrange/Act/Assert

With the advent of BDD, I started naming my classes and expectations as inspired by BDD syntax.  I might have used the [SetUp] attribute or a base class to organize my test code in a style similar to the following:

[TestFixture]
public class when_I_go_to_the_home_page: AAA
{
    private HomeController _controller;
    private ViewResult _result;

    protected override void Arrange()
    {
        _controller = new HomeController();
    }
    protected override void Act()
    {
        _result = (ViewResult)_controller.Index();
    }

    [Test]
    public void then_the_welcome_message_should_be_displayed()
    {
        _result.ViewData["Message"].ShouldEqual("Welcome to ASP.NET MVC!");
    }
}

This actively separates out the different responsibilities of the test.  You can see where the setup code is, as well as the action being tested.  The assertion is the only line of code in the test method.  There is still ceremony involved with the attributes.  Plus, we have added a little more ceremony and noise with the Arrange() and Act() overrides.  This simple test does not necessarily need the parts split in this manner, but it would help with more complex scenarios.  Additionally, the assertion is using extension methods based on the NUnit Assert classes which provides a little more clarity to the assertion.

 

MSpec

Once started down the path of a behavior-driven (or context/specification) style, I started looking at frameworks devoted to that style.  MSpec is one of those frameworks.  Here is the Index action specification in MSpec:

public class when_I_go_to_the_home_page
{   
    Establish context = () =>  _controller = new HomeController();
    Because of = () => _result = (ViewResult)_controller.Index(); 
    It should_display_the_welcome_message = () => _result.ViewData["Message"].ShouldEqual("Welcome to ASP.NET MVC!"); 
    
    static HomeController _controller;
    static ViewResult _result;
}

If you look closely, this specification is very similar to the first NUnit test.  However, there are no attributes to specify and the specification has a distinct functional separation.  The Establish/Because/It syntax is analogous to the Given/When/Then language used in user stories or Arrange/Act/Assert syntaxes used in the previous example.  In my opinion, this has less noise than the test using NUnit with an AAA base class – even while using the lambda delegate syntax.

 

MSpec – SpecificationFor<ClassUnderTest>

I often use a base class to handle some of my setup code. Using StructureMap and RhinoMocks, it generates and injects proxied dependencies for the given class.  In this example, I have no dependencies to wire up, but I think you can still see the benefits.

public class when_I_go_to_the_home_page : SpecificationFor<HomeController>
{
    Because of = () => _result = (ViewResult)ClassUnderTest.Index(); 
    It should_display_the_welcome_message = () => _result.ViewData["Message"].ShouldEqual("Welcome to ASP.NET MVC!"); 
    
    static ViewResult _result;
}

The Establish delegate is not needed in this specification, because I have wired up the class via the base class.  I feel this version is most clear and concise of all the examples, and neither cryptic nor cumbersome  If you are interested in the SpecificationFor<T> base class and the supporting components, check out my previous post

 

Looking to the Future

I hope that this post has shown that MSpec does not have to be cryptic, nor cumbersome.  If you considered it as such before, please take another critical look.

Given the evolving state of the craft, I am sure that my test/specification style will continue to gradually change.  I am sure that my framework of choice will eventually change as well, especially as each framework is extended and challenged by others.  Hopefully, you can be open to evolving your style as well.

Note to self: Asp.Net MVC Controllers are not Code Behind

Sometimes I think things are more complicated than they really are.  I got my head into a bind recently when I had some code that I really wanted under test in a Controller Action.

My first thought was “Crap, this is going to be rough”.  Mainly I was still thinking of my time trying to test Code Behind in Asp.Net WebForms.  I had to smack myself a few times after I remembered that the Controller base class is an abstract type.  Reality is that a Controller doesn’t have to be any harder to test than any other service class.  It isn’t like inheriting from Page (Asp.Net WebForms).

Not that my code did not have some lingering issues.  Like: why did I have something in my Controller Action that would require testing in the first place?  I hate having much logic at all in my Actions.  Get input, send it off for processing (logic), go somewhere.   That should be about it – unless you have to go to different places depending on what is returned.  Now, I want some tests.

Anyway, now back to your regularly scheduled program.

Unity/Moq – AutoMocker or AutoMockingContainer

What is an Auto Mocking Container?

This post started to get a little long, so I won’t re-explain the concept.

Joshua Flanagan wrote a nice overview at his Los Techies blog: Auto mocking Explained.

My post is mainly here to describe the Unity version of an automocking container I threw together.

In Jan 2009 I blogged about my initial version of the Unity AutoMocker – Why am I blogging about it again?

I originally wrote the AutoMocker for the Unity container a year ago (Jan 2009, in Silverlight), and finally got around to placing the code up in the moq-contrib project in June of 2009.

I’m writing another post today in hopes to:

  1. Get some feedback on how this little snippet of code should continue.
  2. Give a little more how-to/example code
  3. Describe some updates I made since I originally created it. 

Where can I get it?

This is one part where I’d appreciate some feedback.

I have two slightly different versions out there (currently).

I have one version at the ElegantCode repository where I was working on it, and the other I threw up at moq-contrib.

The core of the UnityAutoMockContainer is the same in both places, it’s how the tests are separated out that differ.

In the ElegantCode repository it’s an all in one self contained single file (that you can copy into your own test project(s)). You can then setup a single test in your own testing framework that runs all internal automocker tests (in case you need to modify it yourself, and don’t want to break any existing functionality). EX: test

[Test]
public void Should_run_all_UnityAutoMockContainer_internal_tests()
{
    Moq.AutoMocking.SelfTesting.UnityAutoMockContainerFixture
        .RunAllTests(Console.WriteLine);
}

I kind of like this format as it makes it easy to port between test libraries. Can’t say I like having the tests in the same file as the core, but it certainly is not a large chunk of code (so far) so it’s relatively small to maintain and definitely easier to manage as a single .cs file than another assembly (which would have to be version dependent on both Unity and Moq).

The moq-contrib is definitely where I think this helper should end up (and it is there). I just happened to break the tests out into the Silverlight test project and the core is alone in a file.

It’s current state isn’t as easy to copy to a test library (Silverlight/Desktop/Unity 1.2/Unity 2.0) as the one at ElegantCode. What does anyone think? Should I put them all together in one file?

However it ends up (1. all in one file or two (1 test) (1 core)) it will continue to be maintained on the moq-contrib project.

What is the high level API of the container?

It’s pretty simple, (currently) there are four methods on the container.

Two for registering items with the container. Say you want to register an already created instance, or say you want to map an interface to a concrete class and _not_ have the container generate mocks automatically for special cases.

And two for pulling items out of the container. Whether you want a instance of T or a Mock<T>, it gives you ways to retrieve both.

image

How can I setup my own registrations with the container?

Say I don’t want to have the container generate mocks for specific items and I want to supply specific configuration to the UnityContainer.

public UnityAutoMockContainer RegisterInstance<TService>(TService instance)

public UnityAutoMockContainer Register<TService, TImplementation>()

                where TImplementation : TService

Note: both of these registration methods return the container itself so you can fluently stack registration. EX:

AutoMockContainer
    .Register<IServiceA, ServiceA>()
    .Register<IServiceB, ServiceB>();

Let me know: I haven’t tested or played around with how this automocking container deals with any container specific xml configuration… So although I don’t think you should probably have that in a test assembly (stuff happens). Let me know if there are any issues.

How do I get items out of the container?

First is the Resolve<T>(). It will pull an item T out of the container. (Creating it if not already existing)

public T Resolve<T>()

When T is an interface Resolve<T> (unless you setup registration specifically with the container) should return basically “(new Mock<T>()).Object”

When T is a concrete Class, the container should return an instance of T and any of it’s dependencies will be satisfied by mocks. (Note that T will not be any sort of mocked instance of T, unless you used the GetMock<T> as described below first)

public Mock<T> GetMock<T>() where T : class

When T is an interface GetMock<T> should return basically “(new Mock<T>())”

When T is a concrete Class, the container should return a new Mock<T>() and any of it’s dependencies will be satisfied by mocks.

How do I use the UnityAutoMockContainer?

It’s pretty basic, you first create an instance of the UnityAutoMockContainer, and from there you can ask it for mocks of an (Interface, Class, or Abstract Class).

If you request an instance of a concrete class, or abstract class, the UnityAutoMockContainer will stuff mocks in for any constructor dependencies of your concrete class (if it can). You can then request from the container those same dependencies one at a time and either apply mocking setups or verifications.

NOTE: Anything the container creates will live as a singleton instance in the container. So any other requests from the container will always return the originally created instance. Therefore, each distinct scenario in a test suite should have their own instances of the container.

Below his an example of how you can leverage the container in some tests. Given this base fixture class…

public class FixtureBase
{
    private readonly UnityAutoMockContainer _autoMockContainer = new UnityAutoMockContainer();

    protected UnityAutoMockContainer AutoMockContainer
    {
        get { return _autoMockContainer; }
    }

    [TestFixtureSetUp]
    public void SetupContext_ALL()
    {
        Before_all_tests();
        Because();
    }

    [TestFixtureTearDown]
    public void TearDownContext_ALL()
    {
        After_all_tests();
    }

    protected virtual void Before_all_tests()
    {
    }

    protected virtual void Because()
    {
    }

    protected virtual void After_all_tests()
    {
    }
}

If I were given the following system to test.

public interface IServiceA { void RunA(); }
public interface IServiceB { void RunB(); }

public class TestComponent
{
    public TestComponent(IServiceA serviceA, IServiceB serviceB)
    {
        ServiceA = serviceA;
        ServiceB = serviceB;
    }

    public IServiceA ServiceA { get; private set; }
    public IServiceB ServiceB { get; private set; }

    public void RunAll()
    {
        if (!HowDidItGo())
            return;
        ServiceA.RunA();
        ServiceB.RunB();
    }

    public virtual bool HowDidItGo()
    {
        // some really nasty untestable code
        return true;
    }
}

The below example demonstrates simply verifying some behavior on the mocked dependencies of the system under test.

[TestFixture]
public class Example__how_to_pull_items_from_the_UnityAutoMockContainer_when_verifying_behavior_after_an_action_was_taken 
    : FixtureBase
{
    private TestComponent _testComponent;

    protected override void Before_all_tests()
    {
        base.Before_all_tests();
        _testComponent = AutoMockContainer.Resolve<TestComponent>();
    }

    protected override void Because()
    {
        _testComponent.RunAll();
    }

    [Test]
    public void Should_run_ServiceA_RunA()
    {
        AutoMockContainer
            .GetMock<IServiceA>()
            .Verify(v => v.RunA(), Times.Once());
    }

    [Test]
    public void Should_run_ServiceB_RunB()
    {
        AutoMockContainer
            .GetMock<IServiceB>()
            .Verify(v => v.RunB(), Times.Once());
    }
}

Next, you may have noticed that the system under test had a complicated internal method (that may not necessarily be testable). You can use the AutoMocker to create the system under test as a Mock itself, so we can override some of the behavior. Here’s how you could quickly do that.

Aside: I’m not saying this is a good practice or aids in good component design, just saying it’s possible

[TestFixture]
public class Example__how_to_use_the_UnityAutoMockContainer_to_override_a_method_on_the_SystemUnderTest_to_test_a_certain_behavior
    : FixtureBase
{

    private TestComponent _testComponent;

    protected override void Before_all_tests()
    {
        base.Before_all_tests();
        var mockTestComponent = AutoMockContainer.GetMock<TestComponent>();

        mockTestComponent
            .Setup(s => s.HowDidItGo())
            .Returns(false);

        _testComponent = mockTestComponent.Object;
    }

    protected override void Because()
    {
        _testComponent.RunAll();
    }

    [Test]
    public void Should_run_ServiceA_RunA()
    {
        AutoMockContainer
            .GetMock<IServiceA>()
            .Verify(v => v.RunA(), Times.Never());
    }

    [Test]
    public void Should_run_ServiceB_RunB()
    {
        AutoMockContainer
            .GetMock<IServiceB>()
            .Verify(v => v.RunB(), Times.Never());
    }
}

 

It’s amazing how much redundant test setup code this little helper has saved me in my tests. I hope others can find some use with this as well.

StatLight – Goes Open Source

Although I made a very minor attempt at making StatLight a “for-sale” product, I knew when I started that open-source was most likely going to be my long term path for StatLight.

What is it? (Silverlight Testing Automation Tool)

StatLight is a tool developed for automating the setup, running, and gathering results of Silverlight unit tests. StatLight helps to speed up the feedback cycles while practicing TDD/BDD/(insert your test style here) during Silverlight development.

Where can I get StatLight?

http://StatLight.CodePlex.com

Happy Coding !!!

Wrapping up the StructureMap Automocking Container

UPDATE: I apologize…the original wrapper did not allow injected dependencies.  I have fixed this bug and updated the sample.

I have been using StructureMap.AutoMocking with MSpec (Machine.Specifications) and Rhino.Mocks for a few months now.  Although I am very comfortable with the patterns that emerge from using the frameworks together, introducing StructureMap.Automocking to other developers is sometimes challenging.

When viewing a specification or test set up with the Rhino.Mocks or Moq automocking container, what is being tested is not readily apparent.  Once the concept is explained and demonstrated, these same developers seem to have no issue with maintaining the specifications/tests.

I decided to wrap the details of the container to make the intention clearer and explanation easier.  I have started using this wrapper in my projects, and have found it makes building up specifications more efficient in my daily coding.

Let me know whether this is useful to you, or how it could be made more useful.

The Examples

Let’s contrive an example.  We’ll say we have a coffee machine that grinds its own beans before brewing. However, the hopper has to have beans before starting the grind.  Here is the basic specification:

Action/Behavior Prepare coffee grounds for 12 cups of coffee
Expectations Should check that hopper has beans (mock returns true)
Because hopper has beans, should ask grinder to grind enough beans for 12 cups of coffee

We could start without a container, using Rhino.Mocks to build up the CoffeeMachine dependencies manually:

[Subject(typeof(CoffeeMachine),"using vanilla Rhino.Mocks")]
public class Example01_when_preparing_coffee_grounds
{
    Establish context = () =>
        {
            Grinder = MockRepository.GenerateMock<IGrinder>();
            Hopper = MockRepository.GenerateMock<IHopper>();
            Hopper.Expect(x => x.HasBeans()).Return(true);
            CoffeeMachine = new CoffeeMachine(Grinder, Hopper);
        };

    Because of = () => _coffeeMachine.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () => Hopper.VerifyAllExpectations();
    It should_grind_coffee = () => Grinder.AssertWasCalled(x => x.Grind(12));

    static IGrinder Grinder;
    static IHopper Hopper;
    static CoffeeMachine CoffeeMachine;
}

For those of you not familiar with the MSpec style, please refer to the following posts:

[Subject(typeof(CoffeeMachine),"using RhinoAutoMocker<CoffeeMachine>")]
public class Example02_when_preparing_coffee_grounds
{
    Establish context = () =>
        {
            CoffeeMachine = new RhinoAutoMocker<CoffeeMachine>();
            Grinder = CoffeeMachine.Get<IGrinder>();
            Hopper = CoffeeMachine.Get<IHopper>();
            Hopper.Expect(x => x.HasBeans()).Return(true);
        };

    Because of = () => v.ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () => Hopper.VerifyAllExpectations();
    It should_grind_coffee = () => Grinder.AssertWasCalled(x => x.Grind(12));

    static IGrinder Grinder;
    static IHopper Hopper;
    static RhinoAutoMocker<CoffeeMachine> CoffeeMachine;
}

Although I think this looks cleaner, the initialization of CoffeeMachine causes some confusion. Unfortunately, a common question would be, “Is RhinoAutoMocker<CoffeeMachine> creating a mocked version of CoffeeMachine?” Well, not exactly.

RhinoAutoMocker is an implementation of the AutoMocker base class which uses StructureMap to fill dependencies.  The RhinoAutoMocker implementation of the container uses Rhino.Mocks to generate all of dependencies of the target class, whereas the MoqAutoMocker implementation uses Moq.  (Optionally, the target class can be partially mocked in order to further isolate behavior.)  We then retrieve the class under test (in this case, CoffeeMachine) and its dependencies (IGrinder and IHopper) from the container for use.

If you do not need to setup any expectations in the specification, there is no need to retrieve the dependency from the container.  However, in this specification, we need both dependencies.

(Incidentally, I do not like the ClassUnderTest name.  I may end up changing this to Instance, ClassInstance, TargetClass, or something similar.  Suggestions?)

By moving the initialization of the RhinoAutoMocker to a base class, some of the chattiness of the context can be hidden.

    [Subject(typeof(CoffeeMachine),"using RhinoAutoMocker base")]
    public class Example03_when_preparing_coffee_grounds : with_rhinoautomocker
    {
        Establish context = () => Hopper.Expect(x => x.HasBeans()).Return(true);
    
        Because of = () => CoffeeMachine.ClassUnderTest.PrepareCoffeeGrounds(12);
    
        It should_check_if_hopper_has_beans = () => Hopper.VerifyAllExpectations();
        It should_grind_coffee = () => Grinder.AssertWasCalled(x => x.Grind(12));
    
    }
    
    [Subject("using RhinoAutoMocker<T>")]
    public class with_rhinoautomocker
    {
        protected static IGrinder Grinder;
        protected static IHopper Hopper;
        protected static RhinoAutoMocker<CoffeeMachine> CoffeeMachine;
    
        Establish context = () =>
        {
            CoffeeMachine = new RhinoAutoMocker<CoffeeMachine>();
            Grinder = CoffeeMachine.Get<IGrinder>();
            Hopper = CoffeeMachine.Get<IHopper>();
        };
    }

    However, we are still initializing and accessing the class in a less than optimal manner.To make the usage of the container a little more seamless, I decided to create a wrapper and factory for the AutoMocker.  Setup of the dependencies and expectations are done through an AutoMocker wrapper object.  The instance of the class under test is accessed through a ClassUnderTest object.

    The Result

    The specification (and base class) now look like this:

    [Subject(typeof(CoffeeMachine),"using coffee machine base")]
    public class Example05_when_preparing_coffee_grounds : with_coffee_machine
    {
        Establish context = () => Hopper.Expect(x => x.HasBeans()).Return(true);
    
        Because of = () => ClassUnderTest.PrepareCoffeeGrounds(12);
    
        It should_check_if_hopper_has_beans = () => Hopper.VerifyAllExpectations();
        It should_grind_coffee = () => Grinder.AssertWasCalled(x => x.Grind(12));
    }
    
    [Subject("using SpecificationFor<CoffeeMachine>")]
    public class with_coffee_machine : SpecificationFor<CoffeeMachine>
    {
        protected static IGrinder Grinder;
        protected static IHopper Hopper;
    
        public with_coffee_machine
        {
            Grinder = AutoMocker.Get<IGrinder>();
            Hopper = AutoMocker.Get<IHopper>();
        }
    }

    As you can see, the base class inherits from SpecificationFor<T>.  The default constructor uses Rhino.Mocks(MockMode.AAA) to generate the dependencies.  It then exposes a AutoMocker object, which is just the wrapper around the AutoMocker base class.  It also exposes a ClassUnderTest object.  If I didn’t need to use the dependencies, I could make the Example05_when_preparing_coffee_grounds class inherit from SpecificationFor<CoffeeMachine> instead of inheriting from the base class.

    The Code

    I have included the code for the wrapper below for your review.  The code and six examples are available on my Google code repository. The repository also includes an example using the MoqAutoMocker.  All the examples have the same assertions, but are built up using the different techniques.

    namespace CodeProgression.Framework.Testing
    {
        public abstract class SpecificationFor<T> where T: class
        {
            protected static ClassUnderTest<T> Factory;
    
            // UPDATE 2009-12-21:
            //   Moved initialization here
            protected static T ClassUnderTest {get {return AutoMocker.Instance;} }
    
            protected SpecificationFor()
            {
                AutoMocker = AutoMockFactory.CreateTarget<T>();
    
                // UPDATE 2009-12-21:
                //    Initializing here prevented injected dependencies!
                // AutoMocker.PartialMockTheClassUnderTest();
                // ClassUnderTest = AutoMocker.Instance;
            }
    
            protected SpecificationFor(AutoMockType type)
            {
                AutoMocker = AutoMockFactory.CreateTarget<T>(type);
    
                // UPDATE 2009-12-21:
                // Initializing here prevented injected dependencies!
                // AutoMocker.PartialMockTheClassUnderTest();
                // ClassUnderTest = AutoMocker.Instance;
            }
        }
    
        public static class AutoMockFactory
        {
            public static ClassUnderTest<TARGETCLASS> CreateTarget<TARGETCLASS>() where TARGETCLASS : class
            {
                return CreateTarget<TARGETCLASS>(AutoMockType.RhinoMocksAAA);
            }
    
            public static ClassUnderTest<TARGETCLASS> CreateTarget<TARGETCLASS>(AutoMockType framework) where TARGETCLASS : class
            {
                AutoMocker<TARGETCLASS> mocker;
                ServiceLocator serviceLocator;
                switch (framework)
                {
                    case AutoMockType.RhinoMocksAAA:
                        mocker = new RhinoAutoMocker<TARGETCLASS>(MockMode.AAA);
                        serviceLocator = new RhinoMocksAAAServiceLocator();
                        break;
                    case AutoMockType.RhinoMocksClassic:
                        mocker = new RhinoAutoMocker<TARGETCLASS>(MockMode.RecordAndReplay);
                        serviceLocator = new RhinoMocksClassicServiceLocator();
                        break;
                    case AutoMockType.Moq:
                        mocker = new MoqAutoMocker<TARGETCLASS>();
                        serviceLocator = new MoqServiceLocator();
                        break;
                    default:
                        throw new ArgumentOutOfRangeException("framework");
                }
                return new ClassUnderTest<TARGETCLASS>(mocker, serviceLocator);
            }
        }
    
        public enum AutoMockType
        {
            Moq,
            RhinoMocksAAA,
            RhinoMocksClassic
        }
    
        public class ClassUnderTest<TARGETCLASS> where TARGETCLASS : class
        {
            readonly IAutoMocker<TARGETCLASS> _mocker;
            readonly ServiceLocator _serviceLocator;
    
            public ClassUnderTest(IAutoMocker<TARGETCLASS> mocker, ServiceLocator serviceLocator)
            {
                _mocker = mocker;
                _serviceLocator = serviceLocator;
            }
    
            public AutoMockedContainer Container
            {
                get { return _mocker.Container; }
            }
    
            public TARGETCLASS Instance
            {
                get { return _mocker.ClassUnderTest; }
            }
    
            public void MockObjectFactory()
            {
                _mocker.MockObjectFactory();
            }
    
            public void PartialMockTheClassUnderTest()
            {
                _mocker.PartialMockTheClassUnderTest();
            }
    
            public T Get<T>() where T : class
            {
                return _mocker.Get<T>();
            }
    
            public void Inject(Type pluginType, object stub)
            {
                _mocker.Inject(pluginType, stub);
            }
    
            public void Inject<T>(T target)
            {
                _mocker.Inject(target);
            }
    
            public T AddAdditionalMockFor<T>() where T : class
            {
                return _mocker.AddAdditionalMockFor<T>();
            }
    
            public void UseConcreteClassFor<T>()
            {
                _mocker.UseConcreteClassFor<T>();
            }
    
            public T[] CreateMockArrayFor<T>(int count) where T : class
            {
                return _mocker.CreateMockArrayFor<T>(count);
            }
    
            public void InjectArray<T>(T[] stubs)
            {
                _mocker.InjectArray(stubs);
            }
    
            public T Mock<T>() where T : class
            {
                return _serviceLocator.Service<T>();
            }
            public object Mock(Type serviceType)
            {
                return _serviceLocator.Service(serviceType);
            }
            public T PartialMock<T>() where T : class
            {
                return _serviceLocator.PartialMock<T>();
            }
        }
    }