Unit testing code that uses a BackgroundWorker

The BackgroundWorker class is a fantastically simple way of firing off long-running tasks without the complexities associated with threading. However, tests that exercise code that uses a BackgroundWorker may not behave as desired. Unit tests run synchronously, and will not wait for the BackgroundWorker to complete. This article shows an approach which resolves this limitation.

[TestFixture]
    public class TestClass
    {
        [Test]
        public void TestLongRunningOperationCompletesSuccessfullyBadImplementation()
        {
            SomeLongRunningOperation task = new SomeLongRunningOperation();
            task.DoStuff();
            Assert.AreEqual(true, task.IsHit);
        }
    }

    public class SomeLongRunningOperation
    {
        private bool _isHit;

        public bool IsHit
        {
            get { return _isHit; }
        }

        public void DoStuff()
        {
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += delegate
            {
                _isHit = true;
            };
            worker.RunWorkerAsync();
        }
    }

This test will never pass as the unit test runner runs synchronously, so it will not wait for the background work to complete, and the assertion will never be met. Of course, we could put a Thread.Sleep in the test to wait for the task to complete, but this is brittle and as choosing an appropriate time is difficult it will make the test run more slowly.

Instead, we can create a wrapper around the BackgroundWorker class, and an implementation that runs synchronously just for testing.

public class BackgroundWorkerWrapper : IBackgroundWorker
    {
        readonly BackgroundWorker _worker = new BackgroundWorker();

        public void RunWorkerAsync()
        {
            _worker.RunWorkerAsync();
        }

        public void RunWorkerAsync(object args)
        {
            _worker.RunWorkerAsync(args);
        }

        public event RunWorkerCompletedEventHandler RunWorkerCompleted
        {
            add { _worker.RunWorkerCompleted += value; }
            remove { _worker.RunWorkerCompleted -= value; }
        }

        public event DoWorkEventHandler DoWork
        {
            add { _worker.DoWork += value; }
            remove { _worker.DoWork -= value; }
        }

        public bool IsBusy
        {
            get { return _worker.IsBusy; }
        }
    }

    public class SynchronousBackgroundWorker : IBackgroundWorker
    {
        public void RunWorkerAsync()
        {
            DoWorkEventArgs args = new DoWorkEventArgs(null);
            RunWorkerSync(args);
        }

        private void RunWorkerSync(DoWorkEventArgs args)
        {
            DoWork.Invoke(this, args);
            RunWorkerCompleted.Invoke(this, new RunWorkerCompletedEventArgs(args.Result, null, false));
        }

        public void RunWorkerAsync(object arguments)
        {
            DoWorkEventArgs args = new DoWorkEventArgs(arguments);
            RunWorkerSync(args);
        }

        public event RunWorkerCompletedEventHandler RunWorkerCompleted = delegate { };

        public event DoWorkEventHandler DoWork = delegate { };

        public bool IsBusy
        {
            get { return false; }
        }
    }

    public class BackgroundWorkerFactory : IBackgroundWorkerFactory
    {
        public IBackgroundWorker GetWorker()
        {
            return IoC.Resolve();
        }
    }

    public class SynchronousBackgroundWorkerFactory : IBackgroundWorkerFactory
    {
        public IBackgroundWorker GetWorker()
        {
            return new SynchronousBackgroundWorker ();
        }
    }

    public interface IBackgroundWorkerFactory
    {
        IBackgroundWorker GetWorker();
    }

    public interface IBackgroundWorker
    {
        void RunWorkerAsync();
        void RunWorkerAsync(object arguments);
        event RunWorkerCompletedEventHandler RunWorkerCompleted;
        event DoWorkEventHandler DoWork;
        bool IsBusy { get;}
    }

Now we can modify the class that performs the long-running operation to have a backgroundworker factory injected. The production code can pull out the “real” factory via the DI container.

[TestFixture]
    public class TestClass
    {
        [Test]
        public void TestLongRunningOperationCompletesSuccessfully()
        {
            SomeLongRunningOperation task = new SomeLongRunningOperation(new SynchronousBackgroundWorkerFactory());
            task.DoStuff();
            Assert.AreEqual(true, task.IsHit);
        }
    }

    public class SomeLongRunningOperation
    {
        private readonly IBackgroundWorkerFactory _backgroundWorkerFactory;

        private bool _isHit;

        public SomeLongRunningOperation(IBackgroundWorkerFactory backgroundWorkerFactory)
        {
            _backgroundWorkerFactory = backgroundWorkerFactory;
        }

        public bool IsHit
        {
            get { return _isHit; }
        }

        public void DoStuff()
        {
            IBackgroundWorker worker =  _backgroundWorkerFactory.GetWorker();

            worker.DoWork += delegate
                                 {
                                     _isHit = true;
                                 };
            worker.RunWorkerAsync();
        }
    }
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Posted in Uncategorized | Comments Off on Unit testing code that uses a BackgroundWorker

Don’t Swallow Exceptions – Ever

Is there any good reason to do this? I say no. It makes your code run slower, and with tricky to debug errors. Throw exceptions early – then they will be dealt with during development, rather than in production.

We found today that we had some errors in some of our data access code that was pulling data out of a datarow and into an object.

We essentially had code that performed the following:

try
{
   object data = dataRow[ColumnName];
   return data;
}
catch (Exception ex)
{
   Logger.Error(string.Format("Could not retrieve Column value with column name - {0}\n.{1}", ColumnName, ex));
}

This led to our integration tests passing, as they are not able to see that an exception is raised, and the stored procedure needs to be updated with the relevant Column.

Far better would be:

catch (Exception ex)
{
   Logger.Error(string.Format("Could not retrieve Column value with column name - {0}\n.{1}", ColumnName, ex));
   throw;
}

This logs the exception as per the original, but also throws the exception, and voila, our integration test will catch that.

And yes, the fact that we are using Stored Procedures is not ideal either.

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Posted in Uncategorized | Comments Off on Don’t Swallow Exceptions – Ever

Windows Forms Presentation Model Implementation

As mentioned last time, the Presentation Model pattern allows us to decouple our UI Model from our domain model. Briefly restated, this is a good thing, as we do not want UI concerns to leak into our domain model, and we also don’t want our View to contain a lot of logic, as these classes are typically difficult to test and maintain.

This article is going to walk through the code for a really simple example. All we are doing is displaying information about a single book including some extracts from the book. Without further ado, the code for the PresentationModel:

   public class BookPresentationModel : INotifyPropertyChanged
    {
        private readonly IBookService _service;
        private Book _book ;

        public BookPresentationModel(IBookView view, IBookService service)
        {
            _service = service;
            view.SaveChanges += SaveChanges;
        }

        public void Initialise(int bookId)
        {
            _book = _service.LoadBook(bookId);
        }

        public void Initialise(Book book)
        {
            _book = book;
        }

        public string BookName
        {
            get { return _book.Title; }
            set
            {
                _book.Title = value;
                PropertyChanged(this, new PropertyChangedEventArgs("Title"));
            }
        }

        public string ISBN
        {
            get { return _book.ISBN; }
            set
            {
                _book.ISBN = value;
                PropertyChanged(this, new PropertyChangedEventArgs("ISBN"));
            }
        }

        public string Extract1
        {
            get
            {
                if (_book.Extracts[0] == null)
                    return string.Empty;
                return _book.Extracts[0];
            }
            set
            {
                _book.Extracts[0] = value;
                PropertyChanged(this, new PropertyChangedEventArgs("Extracts"));
            }
        }

        public string Extract2
        {
            get
            {
                if (_book.Extracts[1] == null)
                    return string.Empty;
                return _book.Extracts[1];
            }
            set
            {
                _book.Extracts[1] = value;
                PropertyChanged(this, new PropertyChangedEventArgs("Extracts"));
            }
        }

        private void SaveChanges(object sender, EventArgs e)
        {
            Console.WriteLine("Saving...");
            _service.Save(_book);
        }

        public event PropertyChangedEventHandler PropertyChanged = delegate { };
    }
  • The constructor of the PresentationModel class takes all the dependencies the class relies on. In this case, a service which can retrieve information about the book (perhaps to a database), and an instance of the view interface. These will need to be provided via the caller, and ideally via a Dependency Injection container such as Castle Windsor, Unity or StructureMap.
  • The class has a number of properties which encapsulate the domain object. This can flatten or transform the domain object for UI concerns. In our example, The book extracts are pulled out of the list by index, which is easier to bind to a pair of textboxes.
  • If the mapping between domain model and presentation model is more complex, it may be appropriate to have a mapper class that performs this operation. It might be possible to useĀ AutoMapper to perform this, although I haven’t investigated this yet – perhaps a future post.
  • We implement INotifyPropertyChanged and implement it’s single event – PropertyChanged. This event is called in the setter of each property and is required to support binding to controls, especially grids. Notice the empty delegate on the penultimate line, which means we don’t need to perform a null check before raising the event, as it’s invocation list will always contain at least one entry.
  • Events in the view are bound to a method in the Presentation Model between it and the view.
  • The initialise method is called by the caller to either pass an existing Book instance, or a book id to load from the service.

Any comments or suggestions more than welcome.

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Posted in UI, Windows Forms | Tagged , , | Comments Off on Windows Forms Presentation Model Implementation

Logging is good, mmmmkay

Actually, it’s more than good, logging is essential in any application. We wasted a whole load of time today because we weren’t using our standard logging framework (log4net), and the basic logging that was implemented was throwing an error that was effectively swallowed – result – extremely hard to debug errors.

One of our users, reported that his spreadsheet wasn’t working correctly. This sheet connects to an application server via a magical mixture of COM, RTD and remoting. All we got was a mysterious error message from his client dll in our logs telling us to enable custom errors in the service config file. In case you are wondering, this didn’t work, you need to enable custom errors with the code:

 RemotingConfiguration.CustomErrorsMode = CustomErrorsMode.Off;

So, errors received from the server to the client were now more useful. We then had the nice issue of logging not working on the server. We spend some time enabling log4net on the server dll, and voilla, proper debug info.

We could now see that our legacy exception handler was itself throwing an exception due to some string manipulation that wasn’t having it’s boundaries checked.

By the end of the day, we completed a unit test to fix the original bug, plans to create a build script for the server side dlls, and logging introduced throughout the remoting solution, client and server. Frustrating, but ultimately rewarding.

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Posted in debugging, testing | Tagged , , , | Comments Off on Logging is good, mmmmkay

Formatting code in WordPress

OK, so it is my second post, and things are going downhill already.

Meta-Blogging. The first rule of blogging is no meta-blogging.

Someone might find this useful though.

I just figured out how to get nice code formatting with little effort, just by installing a WordPress plugin. This will syntax highlight c#, sql, java, html amongst others.

All you need to do to is search for “Google Syntax Highlighter for WordPress” under Add New Plugin.

Activate the plugin.

This documents how to use the code from within a pre or textarea tag.

Console.WriteLine("That's pretty simple");
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Posted in Uncategorized | Comments Off on Formatting code in WordPress

Presentation Model in Windows Forms

So, certain UI patterns are getting a fair bit of coverage in the .net community currently. Jeremy Miller and Glenn Block for instance, have been posting about this pattern in the past week or so.

My current project has Windows Forms as it’s UI technology. We started off with an MVP approach, and this has worked well, but I experimented recently with a Presentation Model pattern for a data entry grid. It seems to work nicely, and I am reasonably happy with the code, so this series of posts is going to cover how we can implement this pattern with Windows Forms.

Why should I care?

I suspect many (the majority?) of developers put all their code in the View of a screen (Transaction Script). It is very easy to do this, partly because Microsoft doesn’t build anything into the framework to guide UI design, so it is the path of least resistance to add code in the event handlers to talk to the database, perform any business logic, and finally bind to the controls. This is arguably fine for demo code, but leads to a nightmare for maintainability.

The code-behind of the View is not a good place to put application logic. It is difficult (impossible) to write tests against. Important business logic is hidden alongside infrastructure and UI code, and most likely duplicated throughout the application(s). Changes to requirements are difficult to implement as there is no adherence to Single Responsibility Principle.

What is Presentation Model?

Martin Fowler has an extensive article on the Presentation Model.
To quote “The essence of a Presentation Model is of a fully self-contained class that represents all the data and behavior of the UI window, but without any of the controls used to render that UI on the screen. A view then simply projects the state of the presentation model onto the glass.

For me, it is about separating UI logic from application logic.

UI Logic – User interface logic should be kept minimal as possible, and directly related to interacting with UI controls in a particular view. For example, flagging a customer row with a different background colour if they meet a certain condition.

Application Logic – This is what happens when a user interacts with a screen. A button is clicked, an event is raised, actions happen based upon that. The nice thing about having this as a separate object, is that it can be used without the full application being fired up. This saves time, and leads to an improved feedback cycle.

What’s next?

The preliminary plan is to have posts covering the following:

  • View and Data-binding in Winforms
  • Model
  • ViewModel/PresentationModel
  • End to end example

Comments and suggestions welcome.

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Posted in UI, Windows Forms | Tagged , , , , | Comments Off on Presentation Model in Windows Forms