Mocking in Java using Mocha

Ola Bini one of the JRuby guys has released the JtestR tool which allows you to write tests for Java code in Ruby! Ola has bundled a number of Ruby libraries – Mocha, RSpec, Dust, Test::Unit & ActiveSupport – together with JRuby to allow you to write Ruby test cases that test Java code.

He has a couple of examples in the Mock documentation of how to use Mocha

The first one demonstrates using Mocha to mock an interface (Map).

import java.util.Map
import java.util.Iterator
import java.util.Set
import java.util.HashMap


functional_tests do
  test
"that a new HashMap can be created based on another map" do
    map
= Map.new


    map.expects(:size).returns(0)

    iter = Iterator.new
    iter
.expects(:hasNext).returns(false)


    set = Set.new
   
set.expects(:iterator).returns(iter)


    map.expects(:entrySet).returns(set)

    assert_equals 0, HashMap.new(map).size
 
end
end

The second example demonstrates using Mocha to setup expectations on a real (non-mock) instance (HashMap)…

import java.util.Iterator
import java.util.Set
import java.util.HashMap


functional_tests do
  test
"that a new HashMap can be created based on another map" do
    map
= mock(HashMap)


    map.expects(:size).returns(0)

    iter = Iterator.new
    iter
.expects(:hasNext).returns(false)


    set = Set.new
   
set.expects(:iterator).returns(iter)


    map.expects(:entrySet).returns(set)

    assert_equals 0, HashMap.new(map).size
 
end
end