Path: | mock.rb (CVS) |
Last Update: | Mon Jul 26 07:20:56 PDT 2004 |
Ruby/Mock version 1.0
This file contains the Test::Unit::Mockup class, an adapter class for conveniently building mock objects in Test::Unit test cases. It is based on ideas in Ruby/Mock by Nat Pryce <nat.pryce@b13media.com>, which is a class for doing much the same thing for RUnit test cases.
For the examples below, it is assumed that a hypothetical ‘Adapter’ class is needed to test whatever class is being tested. It has two instance methods in addition to its initializer: read, which takes no arguments and returns data read from the adapted source, and write, which takes a String and writes as much as it can to the adapted destination, returning any that is left over.
# With the in-place mock-object constructor, you can make an instance of a # one-off anonymous test class: mockAdapter = Test::Unit::MockObject( Adapter ).new # Now set up some return values for the next test: mockAdapter.setReturnValues( :read => "", :write => Proc::new {|data| data[-20,20]} ) # Mandate a certain order to the calls mockAdapter.setCallOrder( :read, :read, :read, :write, :read ) # Now start the mock object recording interactions with it mockAdapter.activate # Send the adapter to the tested object and run the tests testedObject.setAdapter( mockAdapter ) ... # Now check the order of method calls on the mock object against the expected # order. mockAdapter.verify
If you require more advanced functionality in your mock class, you can also use the anonymous class returned by the Test::Unit::MockObject factory method as the superclass for your own mockup like this:
# Create a mocked adapter class class MockAdapter < Test::Unit::MockObject( Adapter ) def initialize super setCallOrder( :read, :read, :read, :write, :read ) end def read( *args ) @readargs = args super # Call the mocked method to record the call end def write( *args ) @writeargs = args super # Call the mocked method to record the call end end
All the testing and setup methods in the Test::Unit::Mockup class (the abstract class that new MockObjects inherit from) have two aliases for your convenience:
mockAdapter.__setCallOrder( :read, :read, :read, :write, :read )
can be used instead of the call from the example above if the Adapter for some reason already has a ‘setCallOrder’ instance method.
mockAdapter.set_call_order( :read, :read, :read, :write, :read )
will work, too. Double-underscored and non camelCased aliases are not defined; if anyone complains, I’ll add them.
$Id: mock.rb,v 1.1 2004/03/24 02:40:30 neoneye Exp $