Long post ahead, Summary: This post introduces a duck-typing extension for JRuby, extending the possibilities for duck-typing involving java classes. A working prototype is ready for download. Request for comments.

Hi all,

When testing java code (jruby, rspec), I frequently want to test code that takes some argument that I want to mock. If the code looks like this

  public void method1(ISomeInterface param) { ... }

everything is fine. If it looks like this

  public void method2(AClassThatIsReallyHeavyToConstruct param) { ... }

I am in trouble. JRuby doesn't allow me to cloak my ruby classes as java classes (duck-typing), only as java interfaces. Sometimes you can inherit from the class that you want to mock, but as hinted at by the example, this class is really to fat to construct and let's assume that I can't.

So I hacked together a small prototype [3] that allows me to do exactly that, using code I've found in jMock 2. The code allows you to

  ruby_mock = flexmock(:some_mock) # or whatever
  java_mock = DuckType::INSTANCE.transmogrify(ruby_mock,
    AClassThatIsReallyHeavyToConstruct.java_class)

yielding a java class instance that looks exactly like a descendant of AClassThatIsReallyHeavyToConstruct to the JVM, except that it's not. The instance that you get is a proxy class instance that forwards all calls to the ruby_mock object.

This obviously solves my problem and I can continue to test. But it is a kludge; I would really like JRuby to do all this work for me. How about merging this into JRuby? [1] This looks like a nice addition for the java integration to me. [2]

I don't know the JRuby code base well enough to integrate this on my own. I am working on it though - and perhaps someone might be willing to help me with this?

kaspar

[1] Please disregard the bad state of the java code involved. Especially that singleton-pattern is probably out of place. But I hope that you can look at the essence and not at the form. (Which would have to be changed in case of a JRuby integration)

[2] As far as possible, I've made sure that the original authors are credited. I took the jMock ClassImpostorizer and special-purposed it. I am also in contact with the author of the code - he is ok with this new use.

[3] You can fetch the code from http://absurd.li/system/posts/impostor.tgz. You'll need rspec and possibly some other common stuff installed to be able to run the specs. If you use this for your own projects, don't forget to include the .jars in the ./lib dir.


---------------------------------------------------------------------
To unsubscribe from this list, please visit:

   http://xircles.codehaus.org/manage_email


Reply via email to