Last modified 7 years ago
Last modified on 10/15/05 07:22:42
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
- API documentation generated via RDoc.
- The RAA entry for this project.
- Other Ruby Mock stuff:
- Schmock: http://rubyforge.org/projects/schmock/
- FlexMock: http://onestepback.org/software/flexmock/
- RSpec includes a Mock class for doing Behaviour-Driven Development
Downloads
For a complete list of local wiki pages, see TitleIndex.
