cc0f4247a183c1884ad23794fd530e76536dc9f5
test-doubles.md
| ... | ... | @@ -223,6 +223,49 @@ Example: |
| 223 | 223 | |
| 224 | 224 | Our `Converter` provides a means for there to be logging of the conversion. |
| 225 | 225 | |
| 226 | +Let's make a few changes to our design of `Converter`. First off, let's allow that it's easier to |
|
| 227 | +provide configuration parameters via a hash. We'll also provide sensible defaults -- a specific converter |
|
| 228 | +that does nothing and `nil` for the logger. We won't trigger a logger if no logger is set. |
|
| 229 | + |
|
| 230 | +```ruby |
|
| 231 | +class Converter |
|
| 232 | + class PassThroughConverter |
|
| 233 | + def convert(value) |
|
| 234 | + value |
|
| 235 | + end |
|
| 236 | + end |
|
| 237 | + |
|
| 238 | + attr_reader :converter, :logger |
|
| 239 | + |
|
| 240 | + def initialize(args = {}) |
|
| 241 | + @converter = args[:converter] || PassThroughConverter.new |
|
| 242 | + @logger = args[:logger] |
|
| 243 | + end |
|
| 244 | + def convert(value) |
|
| 245 | + converted_value = converter.convert(value) |
|
| 246 | + log(value, converted_value) |
|
| 247 | + converted_value |
|
| 248 | + end |
|
| 249 | + |
|
| 250 | + private |
|
| 251 | + |
|
| 252 | + def log(value, converted_value) |
|
| 253 | + logger.log(value, converted_value) if logger |
|
| 254 | + end |
|
| 255 | +end |
|
| 256 | +``` |
|
| 257 | + |
|
| 258 | +Now, what do we want to verify? We do *not* want to verify that the `log` method on `Converter` gets |
|
| 259 | +called with `value` and `converted_value` -- what we want to know is whether the collaborator is |
|
| 260 | +sent the right message. In this case, we want to know if a logger instance would be sent |
|
| 261 | +the message `log` with the right values. At this point, we don't even have a logger class. We just |
|
| 262 | +know that it is going to expose a method `log` and expect that the method call will pass the |
|
| 263 | +value and its conversion. |
|
| 264 | + |
|
| 265 | +To make this happen, we want to create a `Mock`. |
|
| 266 | + |
|
| 267 | + |
|
| 268 | + |
|
| 226 | 269 | ### Terms |
| 227 | 270 | |
| 228 | 271 | * SUT - System under test |