Class: Mock

Inherits:
Object show all
Defined in:
test/mock.rb

Instance Method Summary (collapse)

Constructor Details

- (Mock) initialize(mock_name = self.to_s)

Creates a new, named mock object. The name is reported in exceptions thrown by the mock object when method invocations are incorrect.



26
27
28
29
30
# File 'test/mock.rb', line 26

def initialize( mock_name = self.to_s )
    @mock_calls = []
    @next_call = 0
    @name = mock_name
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

- (Object) method_missing(name, *args) (private)

Dispatches aribtrary method calls to the next mocked behaviour



71
72
73
# File 'test/mock.rb', line 71

def method_missing( name, *args )
    __mock_call( name, args, (block_given? ? proc : nil) )
end

Instance Method Details

- (Object) __next(name, &test)

Mock the next method call to be made to this mock object.

A mock method is defined by the method name (a symbol) and a block that defines the arity of the method and the mocked behaviour for this call. The mocked behaviour should assert preconditions and return a value. Mocked behaviour should rarely be any more complex than that. If it is, that’s probably an indication that the tests need some restructuring or that the tested code needs refactoring.

If no block is given and preconditions have been defined for the named method, a block is created for the mocked methodthat has the same arity as the precondition and returns self.



45
46
47
48
49
50
51
52
53
54
# File 'test/mock.rb', line 45

def __next( name, &test )
    if test == nil
        if respond_to?( Mock.__pre(name) )
            test = proc { |*args| self }
        else
            raise "no block given for mocked method #{name}"
        end
    end
    @mock_calls.push( [name,test] )
end

- (Object) __verify

Call this at the end of a test to ensure that all scheduled calls have been made to the mock



59
60
61
62
63
64
65
# File 'test/mock.rb', line 59

def __verify
    if @next_call != @mock_calls.length
        raise RUNIT::AssertionFailedError,
              "not all expected method calls were made to #{@name}",
              caller
    end
end