Mock objects for Ruby's Test::Unit

Test::Unit::Mock is a library for conveniently building mock objects in Test::Unit test cases. It is based on ideas in Ruby/Mock by Nat Pryce, which is a library for doing much the same thing for RUnit test cases.

It is designed to let you mock existing classes quickly and easily, but without sacrificing the flexibility to let you do what you need.

Basic Example

class AdminMailer
    def mail_admins( message )
        # ... send emails to all admins
    end
end

class ErrorHandler
    def initialize( mailer )
        @mailer = mailer
    end

    def execute
        begin
            yield
        rescue RuntimeError => err
            @mailer.mail_admins( err.message )
        end
    end
end

require 'test/unit'
require 'test/unit/mock'

class ErrorHandlerTestCase < Test::Unit::TestCase
    def test_error_should_mail_all_admins_with_error_message
        mock_mailer = Test::Unit::MockObject( AdminMailer ).new
        mock_mailer.set_call_order( :mail_admins )
        mock_mailer.activate

        handler = ErrorHandler.new( mock_mailer )
        assert_nothing_raised do
            handler.execute {
                raise "Something bad happened"
            }
        end

        mock_mailer.verify
    end
end

More complex/less-contrived examples of what you can do are on the examples page.

Resources

Downloads

Error: Failed to load processor downloads
No macro or processor named 'downloads' found

For a complete list of local wiki pages, see TitleIndex.