Class: MiniTest::Mock

Inherits:
Object show all
Defined in:
lib/minitest/mock.rb

Overview

All mock objects are an instance of Mock

Instance Method Summary collapse

Constructor Details

#initializeMock

:nodoc:



12
13
14
15
# File 'lib/minitest/mock.rb', line 12

def initialize # :nodoc:
  @expected_calls = {}
  @actual_calls = Hash.new {|h,k| h[k] = [] }
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args) ⇒ Object

:nodoc:

Raises:

  • (NoMethodError)


47
48
49
50
51
52
53
# File 'lib/minitest/mock.rb', line 47

def method_missing(sym, *args) # :nodoc:
  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

Instance Method Details

#expect(name, retval, args = []) ⇒ Object

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


27
28
29
30
# File 'lib/minitest/mock.rb', line 27

def expect(name, retval, args=[])
  @expected_calls[name] = { :retval => retval, :args => args }
  self
end

#original_respond_to?Object



55
# File 'lib/minitest/mock.rb', line 55

alias :original_respond_to? :respond_to?

#respond_to?(sym) ⇒ Boolean

:nodoc:

Returns:

  • (Boolean)


56
57
58
59
# File 'lib/minitest/mock.rb', line 56

def respond_to?(sym) # :nodoc:
  return true if @expected_calls.has_key?(sym)
  return original_respond_to?(sym)
end

#verifyObject

Verify that all methods were called as expected. Raises MockExpectationError if the mock object was not called as expected.



37
38
39
40
41
42
43
44
45
# File 'lib/minitest/mock.rb', line 37

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