2011-02-19 15:44:08 -05:00
|
|
|
######################################################################
|
|
|
|
# This file is imported from the minitest project.
|
|
|
|
# DO NOT make modifications in this repo. They _will_ be reverted!
|
|
|
|
# File a patch instead and assign it to Ryan Davis.
|
|
|
|
######################################################################
|
2008-10-09 21:18:03 -04:00
|
|
|
|
|
|
|
class MockExpectationError < StandardError; end
|
|
|
|
|
2010-12-24 23:55:15 -05:00
|
|
|
##
|
|
|
|
# A simple and clean mock object framework.
|
|
|
|
|
2008-10-09 21:18:03 -04:00
|
|
|
module MiniTest
|
2010-12-24 23:55:15 -05:00
|
|
|
|
|
|
|
##
|
|
|
|
# All mock objects are an instance of Mock
|
|
|
|
|
2008-10-09 21:18:03 -04:00
|
|
|
class Mock
|
2010-12-24 23:55:15 -05:00
|
|
|
def initialize # :nodoc:
|
2008-10-09 21:18:03 -04:00
|
|
|
@expected_calls = {}
|
|
|
|
@actual_calls = Hash.new {|h,k| h[k] = [] }
|
|
|
|
end
|
|
|
|
|
2010-12-24 23:55:15 -05:00
|
|
|
##
|
|
|
|
# Expect that method +name+ is called, optionally with +args+, and
|
|
|
|
# returns +retval+.
|
|
|
|
#
|
|
|
|
# @mock.expect(:meaning_of_life, 42)
|
|
|
|
# @mock.meaning_of_life # => 42
|
|
|
|
#
|
|
|
|
# @mock.expect(:do_something_with, true, [some_obj, true])
|
|
|
|
# @mock.do_something_with(some_obj, true) # => true
|
|
|
|
|
2008-10-09 21:18:03 -04:00
|
|
|
def expect(name, retval, args=[])
|
|
|
|
@expected_calls[name] = { :retval => retval, :args => args }
|
|
|
|
self
|
|
|
|
end
|
|
|
|
|
2010-12-24 23:55:15 -05:00
|
|
|
##
|
|
|
|
# Verify that all methods were called as expected. Raises
|
|
|
|
# +MockExpectationError+ if the mock object was not called as
|
|
|
|
# expected.
|
|
|
|
|
2008-10-09 21:18:03 -04:00
|
|
|
def verify
|
|
|
|
@expected_calls.each_key do |name|
|
|
|
|
expected = @expected_calls[name]
|
|
|
|
msg = "expected #{name}, #{expected.inspect}"
|
|
|
|
raise MockExpectationError, msg unless
|
|
|
|
@actual_calls.has_key? name and @actual_calls[name].include?(expected)
|
|
|
|
end
|
|
|
|
true
|
|
|
|
end
|
2010-12-01 00:33:32 -05:00
|
|
|
|
2010-12-24 23:55:15 -05:00
|
|
|
def method_missing(sym, *args) # :nodoc:
|
2010-12-01 00:33:32 -05:00
|
|
|
raise NoMethodError unless @expected_calls.has_key?(sym)
|
|
|
|
raise ArgumentError unless @expected_calls[sym][:args].size == args.size
|
|
|
|
retval = @expected_calls[sym][:retval]
|
|
|
|
@actual_calls[sym] << { :retval => retval, :args => args }
|
|
|
|
retval
|
|
|
|
end
|
|
|
|
|
|
|
|
alias :original_respond_to? :respond_to?
|
2010-12-24 23:55:15 -05:00
|
|
|
def respond_to?(sym) # :nodoc:
|
2010-12-01 00:33:32 -05:00
|
|
|
return true if @expected_calls.has_key?(sym)
|
|
|
|
return original_respond_to?(sym)
|
|
|
|
end
|
2008-10-09 21:18:03 -04:00
|
|
|
end
|
|
|
|
end
|