Sunday, February 03, 2008

State Based Testing

State based testing is when you exercise one or many methods of an object and then assert the expected state of the object. Many test-driven developers prefer state based tests because they specify as little implementation detail as possible. Tests that specify no implementation details should continue to pass even if the implementation of the methods being tested are changed. The following state based delegation test will continue to be valid for either of the following implementations.

require 'test/unit'

class ShowPresenterTests < Test::Unit::TestCase
def test_delegation_of_name_to_employee
employee = Employee.new("Shane Harvie")
assert_equal "Shane Harvie", ShowPresenter.new(employee).name
end
end

class Employee < Struct.new(:name); end

class ShowPresenter < Struct.new(:employee)
def name
employee.name
end
end

require 'forwardable'
class ShowPresenter < Struct.new(:employee)
extend Forwardable
def_delegator :employee, :name
end

State based tests can contain stubs, but they are generally avoided where possible. State based tests are easy to spot because they rely on assertions to verify the state of the application.

Developers who generally rely on state based tests can be considered Classicists. Martin Fowler has a great article, Mocks Aren't Stubs, that expands greatly on the ideas that are briefly mentioned here.
Post a Comment