Rust: Unit tests in a separate file

In rust, tests are written in the same file as the code. But I want to have the tests in a separate file.

Conventionally, only the integration tests are written in files under tests folder. 1

I just wanted to have the unit tests in a separate file. So I created a file src/my_tests.rs and moved all the tests there.

But cargo test kept saying running 0 tests

Turns out, I’m not the only one. 2

if you don’t import it in main then it doesn’t “exist” as far as the compiler’s concerned. 3

I was able to fix it by adding mod my_tests; to the top of main.rs

It is one thing to read the docs, but real learning comes from actually writing the code. (and making mistakes)


  1. Each file in the tests folder is a separate crate. Which means they can only call functions that are part of your library’s public API. Since unit tests are in the same file as the code, they can access (and test) even the private functions. ↩︎

  2. Stack overflow ↩︎

  3. See this comment ↩︎