I'm a new to Rust. I'm currently building a webserver that works as a standalone. I have main.rs and several submodules. While studying to introduce TDD, I came across the following in the official docs:
Split your program into a main.rs and a lib.rs and move your program’s logic to lib.rs.
I think it's possible to add test while keeping main.rs, but I'm wondering if there's an advantage to splitting it into lib.rs, or if it's a general and implicit promise.
I also have additional questions. Do you prefer adding test module to the bottom of each module(.rs) or creating a test directory to keep them together? I wonder if I need to create a separate test directory to write it.
Are there any advantages to separating lib.rs from main.rs?
I'd say this is more a matter of clean design, not about technical reasons: If you do so, you can easily create multiple binaries sharing code from the lib. E.g., you could create one binary which implements a command line interface and another one with a GUI or a webserver for your library's logic. Testing is also way cleaner and easier if you have a library with a defined API.
Do you prefer adding test module to the bottom of each module(.rs) or creating a test directory to keep them together? I wonder if I need to create a separate test directory to write it.
These are usually used for different types of test. The one in a module are meant for unit tests, which should only but thoroughly test the functionality of that very module. Having the tests there has the advantage, that you can easily access and test non pub
functions in the module.
The tests in the tests
directory are meant for integration tests. These test the public API of the whole library - how it is used by external applications and do the different calls interact correctly with each other.