Description
I'm not sure it's a good idea to have the sentence "Feel free to write some tests for the functionality in the Config::new and run functions on your own" be the end of the opening paragraph of Chapter 12-4. The main reason I think that is because of run
's side effects:
fn run(config: Config) -> Result<(), Box<dyn Error>> {
// talks to the filesystem
let contents = fs::read_to_string(config.filename)?;
// talks to stdout
println!("With text:\n{}", contents);
// --snip--
}
Many programmers will instinctively reach for test doubles when unit testing this function in order to isolate it from IO. As I found out, good, versatile test doubles in Rust are quite challenging to set up for a beginner. I eventually arrived at a solution I was happy with, but it took me 10 hours of reading and coding to get there starting from what I had learned so far, with lots of bumps and false starts along the way. Although I feel a lot more comfortable with Rust's advanced features now, and I'm deeply relieved to know that nice test doubles are possible to implement in it, I don't think the book intends for the reader to go to such great lengths at the beginning of this chapter.
It would be nice if Rust either had stronger first-class supporting for testing, or features that make testing easier, like default parameter values and keyword arguments. In either case, readers could then be lightly introduced to idiomatic versions of these sorts of common testing patterns in Chapter 11, enabling them to write unit tests for run
without much trouble. With the language in its current state, though, that doesn't really seem practical, so I think it might be a good idea to put off discussion of them until readers have gotten more comfortable with traits and generics.
I do get that it's a little weird to launch into TDDing a new feature while there's untested code lying around. Maybe the end of the opening paragraph could say something like, "Feel free to write some tests for the functionality in the Config::new and run functions on your own. Don't sweat it if you find it challenging at this point—it'll get easier as you become more familiar with the type system." I think I would have found my initial difficulty with test doubles less disturbing if I had read that.