6 ms·
I can't figure out whether or not I like this convention. I used to work with a guy who did the same thing with C++ and C# tests: right there alongside the code
by christophilus 10y ago
I can't figure out whether or not I like this convention. I used to work with a guy who did the same thing with C++ and C# tests: right there alongside the code they tested. On the one hand, it is nice to have all of the relevant code in one place for context. On the other hand, it muddied up the actual business logic with tests, so you had to perform some mental work to figure out whether the code you were looking at was for production use or only for testing.
- ryeguy 10y agoIt's worth noting this convention is only for unit tests. Integration tests traditionally have their own test directory and files. Because of this, the file-inlined test code you see is normally relatively simple and shouldn't have a ton of extra helper functions and setup and such. The majority of the code should just be test cases themselves, which are clearly marked with #[test].
- Yoric 10y agoNote that Rust lets you put tests in tests/ instead of src/. So typically, you put short unit tests in src/ and longer/integration tests in tests/. Oh, and examples that show up in the documentation are also run alongside tests. Also, the compiler will tell you if you have code that's not labelled with #[cfg(test)] but is designed to run only in tests.
- tyoverby 10y agoThe big difference with `tests/` is that they have to be integration tests. This means that you can't test private functions from there.
- Manishearth 10y agoNot .. exactly. An integration test usually tests an entire application at once. `tests/` can still test things in the public API (indeed, we do this in Servo a lot) without being an integration test. The point is that some unit tests cannot be written in tests/, whereas all integration tests can be.
- Sean1708 10y agoIt's so that you can do unit testing without having to do weird things like airing your privates in tests, since private modules/functions/etc. aren't visible to your integration tests (which live in tests/ and basically just use your code as a library).
- Tuna-Fish 10y agoI started liking this convention when I started considering the tests documentation. In my code, the first unit test for any function is always the simple common case, and having that right next to the function usually makes the code easier to read.
- steveklabnik 10y agoYou should move it to a documentation block, given that doc examples are also run as tests. Then your users can see them too. Win-win!