I was working through chapter 7 of the book and I decided to try making my own library crate to make sure I understood the module system. The book had an example with
cargo new restaurant --lib, so I tried something similar.
Rather than the tiny "hello world" boilerplate that comes with a binary crate, I was presented with something that had a unit test included. I wrote a library that tested my understanding of the module system, but after coming back to the crate root, I couldn't help but to write unit tests for all of the functions I had organized in my different modules/files.
I've been bamboozled into doing I otherwise can't be bothered to do in other languages! I guess putting thought into the package manager can take something that's easily neglected and make it easy and sorta exciting (for the first time, at least).
Great work to whomever tucked that in there, and everyone that worked on native unit test features.
If you like that, wait until you find out that if you write documentation for your crate, your code examples can serve as de facto unit tests for you as well.
Yes, I love that. The feature is called documentation tests (which also get executed by
Indeed, Rust tests are super low friction to write. While the built-in test framework isn't as powerful as in some other languages (e.g. no built-in parameteric tests, or setup-teardown), the ease of writing simple unit tests far outweights the negative for most library use cases. One can also easily get a bit more power with custom test macros, such as property-testing with proptest or snapshot testing with insta.
Also Rust tests help you to keep private APIs private, without needing to export them for tests, since the inline test modules can access all items of their containing module.
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.