Unit testing singletons

Hi,

How can I properly unit test a singleton? I want to reinitialize it
on every test method, but since it seems to stick around in memory, I
can't seem to ever create a new singleton object.

Thanks,
Joe

Joe Van Dyk wrote:

Hi,

How can I properly unit test a singleton? I want to reinitialize it
on every test method, but since it seems to stick around in memory, I
can't seem to ever create a new singleton object.

Thanks,
Joe

In extremely rear case when I need a singleton nowadays, I usually end up with 2 classes: one is a "normal" class that can be tested and anything and another that is the actual singleton to be used in the application that delegates all missing methods to the first one or simply inherits from it.

Gennady.

"Joe Van Dyk" <joevandyk@gmail.com> wrote in message
news:c715e640506271106cf2347c@mail.gmail.com...
Hi,

How can I properly unit test a singleton? I want to reinitialize it
on every test method, but since it seems to stick around in memory, I
can't seem to ever create a new singleton object.

Thanks,
Joe

Is this what you're looking for?

require 'singleton'

class YourSingleton
  attr_accessor :data
  include Singleton
end

def YourSingleton.instance_for_testing
  @__instance__ = new
end

s = YourSingleton.instance
s.data = 1
puts "s.data=>'#{s.data}'"

# reinitialize instance
t = YourSingleton.instance_for_testing
t.data = 2
puts "t.data=>'#{t.data}'"

w = YourSingleton.instance
puts "w.data=>'#{w.data}'"

# old instance
puts "s.data=>'#{s.data}'"

# output:

···

#
# s.data=>'1'
# t.data=>'2'
# w.data=>'2'
# s.data=>'1'
#

Thanks for the responses. I ended up making it not a Singleton object. :slight_smile:

Joe

···

On 6/27/05, Joe Van Dyk <joevandyk@gmail.com> wrote:

Hi,

How can I properly unit test a singleton? I want to reinitialize it
on every test method, but since it seems to stick around in memory, I
can't seem to ever create a new singleton object.