Alex Coleman
Alex Coleman

Reputation: 647

How to write regression tests for a Rust binary crate?

There's a lot of similar posts in the past 1 2 3 4 but they all seem outdated or irrelevant.

My question is: how do you write regression tests for Rust binaries?

I could set them up as "unit tests" in my src/main.rs file, but that's annoying. Ideally, it would be set up as

root
|---src
    |---main.rs
    |---foo.rs
    |---bar.rs
|---tests
    |---regress1.rs
    |---regress2.rs

Upvotes: 2

Views: 527

Answers (1)

Kevin Reid
Kevin Reid

Reputation: 43773

Two options:

  1. Split your code into a library and a binary: src/lib.rs and src/main.rs. Then you can write tests/ tests that can load the library part.

    This option is best if you specifically want to take advantage of the fact that tests/ tests ("integration tests") are individual binaries on their own (e.g. if the code you want to test uses global variables or system calls that affect global state).

  2. You can write #[test] tests in your binary's code without putting them directly in your src/main.rs file. Just write mod tests; or mod tests { mod regress1; } and put your tests in src/tests/regress1.rs, and in that file write #[test] functions as usual. (Or, if you really want them in a different directory, use the #[path] attribute on mod.)

    This option allows faster test execution, because the tests aren't separate binaries and will be run parallel in threads by the Rust test harness.

Upvotes: 5

Related Questions