Schmock is a simple mock objects library that takes inspiration from flexmock and jmock.
The big difference between schmock and flexmock is that schmock can verify the inputs to methods called.
A simple example (pinched from the flexmock documentation!)
We have a data acquisition class (TemperatureSampler) that reads a temperature sensor and returns the highest of a number of measurements. We don’t have a real temperature to use for testing, so we mock one up with a mock object that responds to the read_temperature message.
Here’s the complete example:
class TemperatureSampler
def initialize(sensor)
@sensor = sensor
end
def highest_temp(number_of_readings = 6)
total = @sensor.last_readings(number_of_readings).inject { |i,s| i+s } return total / number_of_readings end
end
class TestTemperatureSampler < Test::Unit::TestCase
def setup @sensor = SchMock.new @sampler = TemperatureSampler.new(@sensor) end def test_default_highest_temperature_considers_6_measurements
readings = [10, 12, 14, 13, 23, 42]
@sensor.__expects(:last_readings).with(6).returns(readings)
assert_equal 19, @sampler.highest_temp
end
def test_can_vary_number_of_measurements readings = [11,12,13] @sensor.__expects(:last_readings).with(3).returns(readings)
assert_equal 12, @sampler.highest_temp(3)
end
end
More examples can be found in the unit tests