5f0a9949f7eb30dc7fd2c467658e09b745c24d08
test-doubles.md
| ... | ... | @@ -33,6 +33,51 @@ class TemperatureConverterTest < MiniTest::Test |
| 33 | 33 | end |
| 34 | 34 | ``` |
| 35 | 35 | |
| 36 | +### Testing messages received from others -- When to use a stub |
|
| 37 | + |
|
| 38 | +Now let's say that we have a converter object that is capable of a variety of conversions. The |
|
| 39 | +way this is going to work is that we are going to pass in the type of conversion we want, along |
|
| 40 | +with a value to be converted, and we want to get the right result. It will look something like this: |
|
| 41 | + |
|
| 42 | + Converter.new(FToCConverter).convert(32) |
|
| 43 | + |
|
| 44 | +When we test the converter, we are not attempting to establish whether the conversion is correct; |
|
| 45 | +instead, we want to verify that it can delegate the 32 to the specific converter and return the |
|
| 46 | +value. Additionally, we are writing the main converter first. We don't even know the range of |
|
| 47 | +specific converters we are going to want. |
|
| 48 | + |
|
| 49 | +If we create a stub manually, we will want an instance of FToCConverter's convert method to return |
|
| 50 | +a value that we can verify. It might look like this: |
|
| 51 | + |
|
| 52 | +```ruby |
|
| 53 | +require 'minitest/autorun' |
|
| 54 | + |
|
| 55 | +class FToCConverter |
|
| 56 | + def convert(value) |
|
| 57 | + 500 |
|
| 58 | + end |
|
| 59 | +end |
|
| 60 | + |
|
| 61 | +class Converter |
|
| 62 | + def initialize(specific_converter_class) |
|
| 63 | + @specific_converter = specific_converter_class.new |
|
| 64 | + end |
|
| 65 | + def convert(value) |
|
| 66 | + @specific_converter.convert(value) |
|
| 67 | + end |
|
| 68 | +end |
|
| 69 | + |
|
| 70 | +class ConverterTest < MiniTest::Test |
|
| 71 | + def setup |
|
| 72 | + @c = Converter.new(FToCConverter) |
|
| 73 | + end |
|
| 74 | + |
|
| 75 | + def test_f_to_c |
|
| 76 | + assert_in_delta 500, @c.convert(32), 0.01 |
|
| 77 | + end |
|
| 78 | +end |
|
| 79 | +``` |
|
| 80 | + |
|
| 36 | 81 | ### Testing messages sent to others |
| 37 | 82 | |
| 38 | 83 | When we send a message to another object that results in a side effect, we want to verify the side effect. |