Johan Nilsson
1/19/2005 9:08:00 AM
Hi,
I pretty often use small helper classes for my unit tests; call them simple
mock objects or what you like. A trivial example, for the sake of
illustration:
--- tc_myclass.rb ---
require 'test/unit'
class CountingClient
attr_reader :times_called
def initialize
@times_called = 0
end
def on_cb(whatever)
@times_called += 1
end
end
class TC_MyClass < Test::Unit::TestCase
def test_no_of_dispatched_calls
mc = MyClass.new
cc = CountingClient.new
mc.add_listener(cc)
mc.dispatch("A")
mc.dispatch("B")
assert_equal(2, cc.times_called)
end
end
-----------------
My problem comes now when I create a test suite, e.g.
--- ts_myclasses.rb ---
require 'test/unit'
require 'tc_myclass'
require 'tc_myotherclass'
-----------------------
Imagine now that they both define test helper classes named CountingClient,
and that the two definitions of CountingClient differ (well, otherwise
they'd be in a separate file). How should I handle this without naming the
classes "TC_MyClass_CountingClient" etc...
What I did in C++ (for those who are familiar with that) was to always
define such classes inside an anonymous namespace, which means that they are
only accessible within the current compilation unit. A rubyized comparison
would be:
module # Note: no name
class CountingClient
...
end # CountingClient
end # anonymous module
The class CountingClient should then only be accessible within the current
..rb file and take precedence over previous definitions. But no such beast is
available - right?
Regards // Johan