f5017ebc8299631bb76beccd17443d1bf5609c77
test-doubles.md
| ... | ... | @@ -82,7 +82,48 @@ end |
| 82 | 82 | FToCConverter_. All we care about is making available to the test an object that exposes a `convert` |
| 83 | 83 | method that returns a specific value, so that we van validate that the main `convert` method on |
| 84 | 84 | `Converter` leverages it. In short, we want to write the least amount of code to see that the plumbing |
| 85 | -is working. |
|
| 85 | +is working. In MiniTest, it might look like this: |
|
| 86 | + |
|
| 87 | +```ruby |
|
| 88 | +require 'minitest/autorun' |
|
| 89 | + |
|
| 90 | +class FToCConverter |
|
| 91 | + def convert(value) |
|
| 92 | + 500 |
|
| 93 | + end |
|
| 94 | +end |
|
| 95 | + |
|
| 96 | +class Converter |
|
| 97 | + def initialize(specific_converter) |
|
| 98 | + @specific_converter = specific_converter |
|
| 99 | + end |
|
| 100 | + def convert(value) |
|
| 101 | + @specific_converter.convert(value) |
|
| 102 | + end |
|
| 103 | +end |
|
| 104 | + |
|
| 105 | +class ConverterTest < MiniTest::Test |
|
| 106 | + def specific_converter |
|
| 107 | + @specific_converter ||= FToCConverter.new |
|
| 108 | + end |
|
| 109 | + |
|
| 110 | + def setup |
|
| 111 | + @c = Converter.new(specific_converter) |
|
| 112 | + end |
|
| 113 | + |
|
| 114 | + def test_convert |
|
| 115 | + specific_converter.stub :convert, 400 do |
|
| 116 | + assert_in_delta 400, @c.convert(32), 0.01 |
|
| 117 | + end |
|
| 118 | + end |
|
| 119 | +end |
|
| 120 | +``` |
|
| 121 | + |
|
| 122 | +Notice that here our implementation of `FToCConverter#convert` returns 500. But our stub of |
|
| 123 | +this method returns 400: and we verify against that. What this means is that we can check the plumbing |
|
| 124 | +of the delegation to the specific converter even if it's wrong; our stubbed test doesn't depend on |
|
| 125 | +what the actual class does at all: our test is completely independent. Additionally, we have moved the |
|
| 126 | +key verification value closer to the assertion, which is easier to read. |
|
| 86 | 127 | |
| 87 | 128 | ### Testing messages sent to others |
| 88 | 129 |