Exploration Through ExampleExample-driven development, Agile testing, context-driven testing, Agile programming, Ruby, and other things of interest to Brian Marick
|
Mon, 12 Apr 2004Michael Feathers asks for a way for tests to substitute their own mock classes for any class used, however indirectly, by the class under test. That would be simpler than refactoring to pass mocks around in the code under test, though perhaps, in the long run, less desirable. As Michael says, "I'm not convinced that is great thing. Abused it would just let code get uglier without bound. But, used well, it could really help people out of some jams." I undid a bad mood this morning by hacking up something like that for Ruby. Here's an example: require 'test/unit' require 'automock' module DBI # This is a utility used by the class under test. class BigHairyDatabaseConnection def name "true database" end end end module SeparateAppPackage # This class will use the big hairy database connection. # How to mock that out without changing this code? class ClassUnderTest def initialize @database = DBI::BigHairyDatabaseConnection.new end def which_database @database.name end end end class TestSeparatePackage < Test::Unit::TestCase include SeparateAppPackage # Mock out the big hairy database connection. mock DBI::BigHairyDatabaseConnection # Here's what it gets mocked out with. class MockBigHairyDatabaseConnection def name "mock database" end end def test_mock # Notice that the ClassUnderTest magically uses the mock, # not the class it was coded to use. assert_equal("mock database", ClassUnderTest.new.which_database) end end This is just a spike, though I don't offhand see any impediments to a solid implementation. I can finish it up or hand it off if anyone would actually use it. |
|