24

I'm quite confused by how Cargo finds tests to run.

I've created a Cargo project and it added a main.rs for me. If I add #[test] functions in there, they're found and run with cargo test. If I add a foo.rs file as a sibling to main.rs and add tests in there, they're not found and run.

What subtlety am I missing? Do I somehow have to teach Cargo about new files?

Peter Hall
  • 53,120
  • 14
  • 139
  • 204
tenpn
  • 4,556
  • 5
  • 43
  • 63

1 Answers1

36

Cargo will not just compile any files that happen to be in your source directory. In order for Cargo to find a file, it must be referenced as a module either in main.rs/lib.rs or from some sub-module.

For example, in your main.rs:

mod foo;

That's it.

Peter Hall
  • 53,120
  • 14
  • 139
  • 204
  • 1
    Would you idiomatically put unit tests in their own file, and have prod mode mod them in? Or just put the tests in the file of the thing under test? – tenpn Jul 02 '17 at 18:07
  • 13
    Does anyone find this behaviour weird or is it just me? – Afaq Jun 27 '18 at 19:49
  • 1
    @Afaq I found it confusing at first because it's different to languages that I'm used to. But it doesn't seem strange to me now. It's an entirely logical approach, just with a different set of tradeoffs from, say, Java. – Peter Hall Jun 27 '18 at 19:57
  • 2
    @PeterHall Yes, it is a bit confusing. Although, I found this very interesting blog about organising tests in Rust http://sireliah.com/niusy/testing_in_rust/ – Afaq Jun 27 '18 at 21:04