unit testing singletons

J

Joe Van Dyk

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
 
G

Gennady Bystritksy

Joe said:
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.
 
S

Sean Ross

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'
#
 
J

Joe Van Dyk

Hi,
=20
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 for the responses. I ended up making it not a Singleton object. :-=
)

Joe
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
474,175
Messages
2,570,942
Members
47,489
Latest member
BrigidaD91

Latest Threads

Top