Sunday, July 26, 2009

unit testing private methods in ruby

don't u just love this???

class Class
def publicize_methods
saved_private_instance_methods = self.private_instance_methods
self.class_eval { public *saved_private_instance_methods }
self.class_eval { private *saved_private_instance_methods }

and to test the private method blah of a class Foo

class TestFoo &Test::Unit::TestCase
def test_blah
Foo.publicize_methods do
assert_not_nil Foo.blah

and thats it... :)

1 comment:

dog said...

I didn't know ruby had private methods (Python doesn't, and usually uses _ before methods to denote that. There's also an __ name mangling thing which no one uses :). I had heard that ruby methods can be overwritten even if it's builtin.

In java, you can get the java.lang.reflect.Method object and do a setAccessible(true) and invoke it. Invoking is a bit clunky but it'll get the job done. (In c# similar thing is possible, and if we can utilize the new dynamic keyword, then invocation won't be clunky. I haven't checked this though)