unit testing - How to Mock Static Java methods with JRuby and Mocha? -


my goal unit test legacy java code, riddled static utility methods, using jruby , mocha. possible?

i trying apply similar techniques available in jmockit; framework leveraging proxies change test behavior dynamically. purists may suggest refactoring out static methods, @ point, it's not possible.

i put 2 unit tests:

test #1 - ruby mocking - control.
test #2 - java mocking - see if can accomplish same in java.

for both tests, i'm replacing "gettax" method.

here code:

test 1

require 'rubygems' require 'dust' require 'mocha'  unit_tests      # test 1 - stub out jruby secondary class , override "gettax" method     # "control" - i'm overriding tax multiplier 1.15 1.18.     # works =)     test "rubymocking"         # system under test         class rinvoice              def initialize                 @util = rinvoiceutil.new             end             def calculate                 @util.gettax * 10.0             end         end          # dependency         class rinvoiceutil              # we'll stub out method , change tax rate             def gettax                 1.15             end         end          invoice = rinvoice.new               # change tax rate         rinvoiceutil.any_instance.stubs(:gettax).returns(1.18)               assert_equal(invoice.calculate.to_s, "11.8")     end end 

test 2

include java  require 'rubygems' require 'dust' require 'mocha' require 'invoice.jar' invoice = java::example.invoice invoiceutil = java::example.invoiceutil  unit_tests  # test 2 - stub out java class invoiceutil , it's *static* gettax method. # can achieved via jmockit, possible in mocha?    test "javamocking"     invoice = invoice.new            # not work because ruby objects      # proxies java objects?     invoiceutil.any_instance.stubs(:gettax).returns(1.18)            assert_equal(invoice.calculate, 11.8)      end end 

test 2 fails with: <11.5> expected <11.8>. ok, can't that. hmm. reason not work because ruby objects proxies java objects?

java source

package example; public class invoice {     public double calculate() {         return invoiceutil.gettax() * 10.0;     } }  public class invoiceutil {     public static double gettax() {         return 1.15;     } } 

to sum up

all want combine static method mocking jruby leverage (1) easy scripting (2) flexibile test isolation.

thanks in advance responses!

i haven't used myself, ola bini released jtestr while ago might you're looking for. looks has addressed any_instance problem seeing above. have no idea how up-to-date jtestr is, looking @ ola's github account there recent commits, in luck. hope helps.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -