Tigraine
Daniel Hoelbling talks about .NET

Beggars can’t be choosers: Dependency injection through global factories

October 14th, 2009 . by Daniel Hölbling

Whenever you listen to testability talks you usually take away one universal truth:

Global state is bad, singletons are essentially global state.

So, if you want to have it done right, use dependency injection and don’t let your code depend on global state.

But: Sometimes it’s just not possible. My current project for example does not use dependency injection. Why? I didn’t know better and used ActiveRecord with all it’s static design. And besides, I’m just lazy and have no intention of diving into the Castle documentation to find out how to teach ActiveRecord to use an IoC container when creating entity objects.

And if you have no control over your constructor, your options for dependency injection are limited to two things:

Public fields (aka optional dependencies) and Global factories.

Public fields

While in theory a pretty decent method that allows you to swap out parts it falls very short once you have multiple classes that need the same service:

public class Entity
{
    public IDateProvider DateProvider { get; set; }

    public Entity()
    {
        DateProvider = new DateProviderImpl();
    }
}

Since the default implementation is hardcoded into every consumer, you end up with a big pile of DRY violations that will one day bite you when you try to refactor DateProviderImpl’s constructor.

Global factories

Now the words global and testability don’t go well together, but in this case it’s ok. You try to battle the DRY violation while still making your service optionally interchangeable when testing.

public class Entity
{
    public Entity()
    {
        var now = DateProviderFactory.Provider.Now;
    }
}

public class DateProviderFactory
{
    private static IDateProvider _provider;

    public static void SetProvider(IDateProvider provider)
    {
        _provider = provider;
    }
    public static IDateProvider Provider
    {
        get
        {
            if (_provider == null)
                _provider = new DateProviderImpl();
            return Provider;
        }
    }
}

Now obviously you should NEVER call SetProvider inside your production code. It’s a pure testability helper so if you start messing with it expect to see some really hard to debug errors pop up.

But as long as you don’t mess that up, you can write tests like this one:

public class TestFixture
{
    [Fact]
    public void DoesSomethingWhenGivenDate()
    {
        var mock = new MockedDateProvider();
        DateProviderFactory.SetProvider(mock);
        var entity = new Entity();
        //.....
    }
}

I know it’s not perfect, but nobody expected it to be that way. The best solution to the problem obviously is a very clean separation of object construction and business logic, and the proven way to achieve that is dependency injection through a container like Windsor or StructureMap. Yet, often you have to look at old codebases where you just need to get the job done, and then it’s nice to know your way around the limitations sometimes.

Oh, and btw: The example I did above was chosen deliberately to be something as simple as a abstraction of DateTime.Now. As said before, never depend on moving parts in your tests.


Don’t forget the Refactor in Red-Green-Refactor

July 1st, 2009 . by Daniel Hölbling

When first learning about TDD all sources I read focused pretty much on one thing: writing the tests.

Few sources really talk about the full TDD workflow:

  • Write a failing test
  • Make it pass
  • Refactor the code
  • start over

Arguably that the hardest part of doing TDD is 1+2, while possibly the most important one is 3!

Some people tend to stress the fact that automated tests can be a safeguard against breaking existing code. And although I like this aspect, I believe if your code is structured well and was built with the open-closed principle in mind,  chances are you’ll never touch old code in the process of implementing new features.

But during refactoring, you play to TDDs strengths. You don’t write new stuff, you focus on the stuff that’s already there and that already works. You search for ways to improve what’s already there while not changing it’s behavior. And very often this final refactoring step is the only thing that really brings value to your process, since it not only uses those tests you just wrote, it also facilitates future change allowing you to produce cleaner code than you would without refactoring.

Think of refactoring as fortifying the wall you’ll be building the next floor upon. Without it the you may be fine, but 3 floors from now you’ll have a lot of work at your hands to be able to commence work.

Getting things right the first time is incredibly hard. On my last project it even took me some quality pair programming once to come up with something great, and 80% of the pair programming was mostly spent on refactoring a raw idea from a 80% solution into a 100% solution. So, don’t spend too much time with hunting the ideal of writing a 100% solution the first time, rather try to get it 80% right and don’t stop improving it until you are at 100%!


.NET Unit testing tools

May 31st, 2009 . by Daniel Hölbling

After posting my tools list today I got asked why I didn’t list any testing frameworks. Obviously, I love testing, so why no testing tools like Gallio, NUnit or Testdriven.NET etc?
The answer is rather simple, Resharper runs my tests for me.

By default Resharper can run NUnit tests, if you install Mbunit it can run those too, and if you just copy over the resharper support library from the XUnit contrib project to your Resharper/Plugins directory it can also run XUnit.

image

Also, almost all open source frameworks out there include their test runner in their code tree, so you don’t need to worry about what exotic test frameworks are out there, you’ll be provided with the appropriate runners.

On the testing framework side I recently (~4 months) switched over to xUnit as it’s syntax felt much better than that of xUnit or Mbunit.
Also I am currently looking into maybe using a BDD testing framework like MSpec.


Troublesome testing

May 21st, 2009 . by Daniel Hölbling

This may be the very first time I blog about a bug in the CLR, but it’s annoying nonetheless.

Apparently a bug in the CLR’s System.Reflection.Emit prevents Rhino.Mocks from working when generic constraints are applied to a method.

void Add<T, TType>()
    where T : class
    where TType : T;

As long as the TType : T constraints is present, all tests will fail with a System.BadImageFormatException.

Now, the bug is known and it looks like it can’t really be helped on the framework side. But, I didn’t want to drop this constraint in my production code just to make the class testable.

So, I went back to the dark ages and actually wrote a Mock class by hand that counted calls to methods, returned preset values for methods.

Overall, the Mock is a mess. There are like 5-6 fields counting all sorts of different stuff just for a simple interface with two methods.

Thank god there are tools like Rhino.Mock that keep me from writing code like that (I really can’t praise Ayende enough for Rhino.Mocks).


Tests should last forever

March 25th, 2009 . by Daniel Hölbling

There is one excellent point Roy Osherove made while reviewing the tests in NerdDinner.com I wanted to share with you.

Don’t write tests that change over time!

Often I have initialized objects for tests like this:

[Fact]
public void Test()
{
    DateTime date = DateTime.Now;
    ...
}

Until recently I thought that’s cool, after all the tests passed every time I ran them.

But what if the passing tests are just a coincidence?

What if I am testing a financial application that will only accept orders between 8am and 6pm on weekdays, and the order-date gets initialized to DateTime.Now in my test?

Given the normal work days in most countries that code would run for most developers just fine, but when some notorious late-worker like me comes in the tests start failing for no apparent reason.

Time or place of execution, should not have an impact on a test at all. Given the same code and the same test, the result should always be the same.

So, whenever you initialize a value to something from your current execution context (time being the prime example here), you create a possibility that this test will break in some unexpected ways over time.

So if you really want to fill some DateTime with a value for testing use a constant (like DateTime.MinValue/MaxValue). So whenever you re-run this test all inputs are the same as they have been when you wrote the test.


ASP.NET MVC: Hide the HttpContext services with Windsor and a custom ControllerFactory

January 21st, 2009 . by Daniel Hölbling

ASP.NET MVC was designed to be a very “clean” and testable framework for creating web applications from Microsoft. And they failed really badly in one place: HttpContext!

The fact that the ASP.NET MVC Contrib project has a whole project dedicated to mocking out the whole HttpContext for testing simply illustrates one point: It’s broken, period.
There is this one gigantic god hash table that has 5 other hash tables hanging from it that knows everything about the incoming request. And although it’s possible to fake the whole thing with RhinoMocks (as the MVC Contrib guys do it), it’s still a pretty stupid idea to have all those concerns in one class called “context” (and accessible to the controller code).
So, although the HttpContextBase is already an abstraction of the real context, I wanted to extract those things into specialized service classes that I have full control over (and that could then be used for even more specialized classes that handle data retrieval, thus making “magic strings” go away when dealing with requests and sessions).

I set out to create a request service class that follows a very simple Interface:

public interface IRequestService
{
    string GetRequestField(string fieldName);
}

The actual class is just a Facade for the HttpRequestBase class that gets injected into the constructor.

Problem here: I would have to new up this IRequestService in my controller, and that’s something I didn’t want to do. Object graph construction shouldn’t be in the controller at all, and so I want to inject IRequestService instances into the controller. And that can’t be done without control over the ControllerFactory.

The IControllerFactory interface is rather simple, and it’s the perfect place to leverage the power of a IoC framework to construct the controller objects.

So I simply pass the object creation off to Windsor in the CreateController method:

public class ControllerFactory : IControllerFactory
{
    private WindsorContainer container = new WindsorContainer(
                                        new XmlInterpreter(new ConfigResource("castle")));

    public IController CreateController(RequestContext requestContext, string controllerName)
    {
        
        return (IController)container.Resolve(controllerName);
    }

    public void ReleaseController(IController controller)
    {
        var disposeable = controller as IDisposable;
        if (disposeable != null)
            disposeable.Dispose();
        container.Release(controller);
    }
}

What then took ages for me to figure out was how to instruct Windsor to use current HttpContext.Request object. Turns out, I was searching in the wrong place: That functionality is in MicroKernel and not in the Windsor container.

public IController CreateController(RequestContext requestContext, string controllerName)
{
    container.Kernel.AddComponentInstance<HttpRequestBase>(typeof (HttpRequestBase),
                                                           requestContext.HttpContext.Request);
    return (IController) container.Resolve(controllerName);
}

The AddComponentInstance method allows you to pass in a concrete instance that should be used when searching for a service. This way when Windsor constructs the RequestServiceFacade class that takes a HttpRequestBase as dependency it will simply inject the one specified instead of trying to construct the HttpRequestBase itself (that doesn’t work ;) ).

This now allows me to easily swap out request implementations by just changing the Windsor configuration.


Practices you don’t throw away when your deadline approaches

December 5th, 2008 . by Daniel Hölbling

6358304_cd37b36deb
(image by deVos)

So, I’m a bit under pressure right now. I don’t blog too much because I’m bound to a immutable release date of 7th of January. If I don’t get the software out until 7th of January the customer will have to wait for another year before he can make the switch from his (pain in the ass) 15 year old MS-DOS software.

So you see I’m not only a little bit stressed, I’m looking forward to a Christmas holiday I’ll probably spend locked into some room finishing the software day and night.
As that deadline approaches, there are some things I have noticed in my current development that suddenly don’t seem fit any more due to time constraints.

I know my business layer needs a major refactoring (a day or so) to keep my domain logic “clean” of clutter. But I know I can’t spend a day refactoring something that has to ship next week (I want to have the app user tested by 7th). Still I can think before I code.
One thing I see in legacy code all the time is how people stop thinking once they approach deadlines, but start to just mindlessly copy/paste stuff to make it work somehow.

Here’s one principle you should NEVER forget:

DRY – don’t repeat yourself

Not repeating yourself through simple copy and paste will at least make it easy for you not to have to rewrite the whole thing once a change has to be made. I can retrofit extensive tests and good SoC, but I am doomed once I have to change the same piece of code throughout the whole application.

If I’m so stressed that I have to write crappy code, It’s still my duty to fix it sometime later, and that’s not possible if  one business rule (it may be as simple as amount/numberOfRates) is done at 20 different places!
That then leads me to the next point, fixing stuff later requires at least some automated tests (nothing is worse than writing fixes that have more bugs in them).

Testing isn’t difficult, and it saves you more time than it takes. You may think you’re faster if you run the app once and see if it works, but apps don’t run as fast as unit tests, and once you have to run it several times to make it work you would have saved time by writing a unit test first. And although my tests look ugly and may be incomplete, I have verified that the most important calculations and interactions work (and can rerun those tests and verify that stuff still works later when I try to clean up the mess).

So, by applying (even incomplete) testing to my app, and not violating DRY I still retain the ability to easily extend and manipulate my application in the future. Once I’m done I can easily run NCover and find out what code I didn’t cover in my tests..


Cheap Bugtracking systems

November 10th, 2008 . by Daniel Hölbling

I don’t like documentation.
Whenever I feel that I need to add comments to a piece of code to make it understandable I usually rework the code until it’s intent and workings are clear from looking at it.

Still, documentation will come after you once you are dealing with defects and planned features. Nobody can keep that stuff in their head, and it’s important to keep track of what your customers expect you to do/fix.

And while big projects demand some “real” process around this issue, when you’re doing small projects you usually don’t want to break a butterfly upon a wheel.

One easy solution is to simply write a Unit Test that exposes the bug.
Whether you fix it right away or you check it into your source-tree is totally up to you, but you’ll always see that red light reminding you of that bug.

While at it, I strongly suggest always writing a Unit Test to expose a bug prior to fixing it. You increase your code coverage by fixing bugs, and protect yourself from having the bug surface again with a later change.

Still, you should also look into getting a “real” bugtracking databases like FogBugz (has a free 2 person license), or install your own like Trac or BugNET.


Unit testing with mocks – Rhino Mocks basics (Part 2)

November 5th, 2008 . by Daniel Hölbling

In Part1 of this series I have showed you how to create a very simple mock object by hand. In this post I will show you how to use RhinoMocks to create the mock and how to verify this. This post is intended as basic advice, and won’t cover any advanced RhinoMocks topics, just the basic setup/replay/verify steps.

When working with almost any mock framework there are 3 things: Setup, expectation recording and verifying that the expectations where met.
That means, first you tell the mock object what calls to expect. Then you let the method under test do it’s magic and afterwards you let the mock verify that all expected calls where made.
You can get very precise on what to expect and how to expect it, but that will be covered in the next part of this series.

The hand-made mock from Part1 would translate to a test like this when using RhinoMocks:

[Test]
public void ServiceWatcherNotifiesUser()
{
    var repository = new MockRepository();
    var notifier = repository.StrictMock<IErrorNotifier>();

    notifier.NotifyOfServiceDown();

    repository.ReplayAll();

    var watcher = new HttpServiceWatcher(notifier);
    watcher.ObserveService();

    repository.VerifyAll();
}

The main things here:

We start the repository and then request a IErrorNotifier object from it.

var repository = new MockRepository();
var notifier = repository.StrictMock<IErrorNotifier>();

The mock object (notifier) is in record mode now, all calls we do to the object aren’t actually executed but will be expected afterwards.

So if we want NotifyOfServiceDown to be called once we simply call it while in record mode:

notifier.NotifyOfServiceDown();

After having set up all expectations in record mode, we tell the Mockrepository to go to replay mode:

repository.ReplayAll();

The mock object still doesn’t do anything. But it expects what we setup in replay. If the watcher calls methods that weren’t specified in replay mode the mock will throw exceptions at us.

Now we construct the object under test:

var watcher = new HttpServiceWatcher(notifier);

And note that we pass the mock object instead of an actual implementation of IErrorNotifier.

Now we call the method under test just as we would normally:

watcher.ObserveService();

That leaves us with only one step left, we tell the repository to verify all mocks that where created and it will throw Exceptions if mocks didn’t get called or did get called too often.

repository.VerifyAll();

Although this is just a very basic example of how to use RhinoMocks, you are able to see the benefits from this. You could write the HttpServiceWatcher class without having to write any concrete IErrorNotifier implementations. You can just concentrate on the HttpServiceWatcher instead of worrying how the underlying Service is going to work.

In the next part I’ll be covering how to make some fancier things with RhinoMocks like returning values and verifying that passed parameters meet certain criteria.

The source code is available through my SVN repository:

svn checkout https://office.pixelpoint.at:8443/svn/tigraine/UnitTesting/trunk UnitTesting –username guest

Notice that all dependencies are also in the svn, so you don’t need to get RhinoMocks or nUnit yourself.


Unit testing with mocks (Part 1)

November 4th, 2008 . by Daniel Hölbling

I regret not having blogged on TDD and designing for test before – it makes it very difficult to talk about mocking as it is a rather advanced topic, requiring at least some knowledge of polymorphism and oo-design.
So this post is the first in a series of posts on the topic of testing with mock objects, that will hopefully help you with your testing.

Testing is one of the most important things in software development.
We’re all human, and we all make mistakes. And even if we discover these mistakes during development and testing, it’s almost certain that we’ll have to come back at a later point to change something, possibly breaking what already worked.
Doing a full QA cycle during initial development may look reasonable to most of us, but doing it every time you change a tiny bit in the application will certainly get you some angry mails from management.
Having good unit tests gives you a safety net for future development. By simply running the tests you can verify that things that already worked still work properly. And that’s what is important in software development.

The whole idea of unit testing is to test as little as possible while still verifying that the method under test behaves as specified and expected.
Keep this in mind, because it is important when testing classes that depend on services or other classes.

If let’s say you have a HttpServiceWatcher that is a service running somewhere and watching if a HttpService is up and running, you should test the HttpServiceWatcher class itself, not the associated notifier classes that the Watcher calls when it wants to notify you.
But how do you verify that the HttpServiceWatcher really worked and called the notifier as a result?

Let’s start with the Notifier interface:

public interface IErrorNotifier
{
    void NotifyOfServiceDown();
}

Let’s assume we have implemented a EmailNotifier class, if the HttpServiceWatcher looks like this we’re in testing-nightmare land:

public class HttpServiceWatcher
{
    public void ObserveService()
    {
        IErrorNotifier notifier = new EmailNotifier();
        notifier.NotifyOfServiceDown();
    }
}

The HttpServiceWatcher news up it’s notifier service, so every time we want to adjust the notifier, we’d have to change the ServiceWatcher and risk breaking something. Also, we can’t test the ServiceWatcher itself, because it will always call to an EmailNotifier that we can’t fake easily.

So, the correct move would be to use Inversion of Control (IoC) to inject the service into the watcher class:

public class HttpServiceWatcher
{
    private IErrorNotifier notifier;

    public HttpServiceWatcher(IErrorNotifier notifier)
    {
        this.notifier = notifier;
    }

    public void ObserveService()
    {
        notifier.NotifyOfServiceDown();
    }
}

Now, the HttpServiceWatcher class doesn’t directly depend on any concrete implementation of IErrorNotifier, the calling code takes care of creating the concrete classes. Changes to notifiers don’t get propagated to the HttpServiceWatcher.

Also, this makes it very easy to simply fake the notifier. We could either create a fake test class that inherits IErrorNotifier, or we could use a Mocking framework.

Manual mocking could look like this:

public class NotifierMock : IErrorNotifier
{
    public int notifyOfServiceDownCallCount = 0;

    public void NotifyOfServiceDown()
    {
        notifyOfServiceDownCallCount++;
    }
}

The test could then look like this:

[Test]
public void ServiceWatcherNotifiesUser_Custom_Mock()
{
    var notifier = new NotifierMock();

    var watcher = new HttpServiceWatcher(notifier);
    watcher.ObserveService();

    Assert.AreEqual(1, notifier.notifyOfServiceDownCallCount);
}

And that’s fine. It works, we verify that the watcher actually calls the notifier service, and all is well.

It just gets tricky when you get more tests, you’ll have to create many mock objects that always introduce the possibility of breaking other tests etc.

In the next post in this series I will try to illustrate how to do the same thing with RhinoMocks and how it makes testing very easy.

Download the source code from my SVN Repository by doing a:

svn checkout https://office.pixelpoint.at:8443/svn/tigraine/UnitTesting/trunk UnitTesting –username guest

Continue reading Unit testing with mocks – Rhino Mocks basics (Part 2)