Testing Singleton classes

Testing Singleton classes can be a bit of a problem. The fundamental idea of a Singleton is that a class should have one and only one instance. However, one of the fundamental principles of testing is that tests should be atomic – you create a new instance of the object being tested before running each test.

As you can imagine, this kinda sorta totally doesn’t work out.

Fortunately the Singleton module in Ruby’s standard library provides a fairly easy way out of this. If you were testing a RemoteControl class, you could “reset” the Singleton instance like so:

Singleton.__init__(RemoteControl)

Simply place that in your teardown method and you’re sorted: you still get the security of only having one instance of RemoteControl, but the slate is wiped clean after each test.

Posted on Monday, June 18, 2007.

Post a comment

You may use Textile for formatting.