Hardmock

Strict, ordered mock objects using very lightweight syntax in your tests.

DISCONTINUED

After release 1.3.8, Hardmock will not be actively maintained. (1.3.8 is a Ruby 1.9/MiniTest compatibility update, see below).

Atomic Object still believes in (and heavily utilizes) mock objects and interaction-based unit testing, however, we ourselves have begun leveraging other popular mocking tools such as RSpec, RR, Mocha, etc.

For those of you with time invested in older projects using Hardmock, but who need to migrate their older projects to Ruby 1.9, try updating to Hardmock 1.3.8.

How to use Hardmock

The basic procedure for using Hardmock in your tests is:

  • require ‘hardmock’ (this happens automatically when being used as a Rails plugin)

  • Create some mocks

  • Setup some expectations

  • Execute the target code

  • Verification of calls is automatic in =teardown=

The expectations you set when using mocks are strict and ordered. Expectations you declare by creating and using mocks are all considered together.

  • Hardmock::Mock#expects will show you more examples

  • Hardmock::SimpleExpectation will teach you more about expectation methods

Example

create_mocks :garage, :car

# Set some expectations
@garage.expects.open_door
@car.expects.start(:choke)
@car.expects.drive(:reverse, 5.mph)

# Execute the code (this code is usually, obviously, in your class under test)
@garage.open_door  
@car.start :choke
@car.drive :reverse, 5.mph

verify_mocks # OPTIONAL, teardown will do this for you

Expects @garage.open_door, @car.start(:choke) and @car.drive(:reverse, 5.mph) to be called in that order, with those specific arguments.

  • Violations of expectations, such as mis-ordered calls, calls on wrong objects, or incorrect methods result in Hardmock::ExpectationError

  • verify_mocks will raise VerifyError if not all expectations have been met.

Download and Install

Setup for Test::Unit

require 'hardmock'
require 'assert_error' # OPTIONAL: this adds the TestUnit extension 'assert_error'

NOTE: If installed as a Rails plugin, init.rb does this for you… nothing else is needed.

Setup for RSpec

Get this into your spec helper or environment or Rakefile or wherever you prefer:

Spec::Runner.configure do |configuration|
  configuration.include Hardmock
  configuration.after(:each) {verify_mocks}
end

This puts the implicit conveniences into your spec context, like “create_mocks” etc, and also provides for automatic “verify_mocks” after each Example is run.

Ruby 1.9 Compatibility

As of build 1.3.8, Hardmock works in Ruby 1.9.2. Older versions of Hardmock had non-1.9 compatible code; furthermore, 1.9 ships with MiniTest, which is similar to TestUnit but has different implementation internals, which we monkey-patch.

Author