I created a new binary using Cargo:
cargo new my_binary --bin
A function in my_binary/src/main.rs
can be used for a test:
fn function_from_main() {
println!("Test OK");
}
#[test]
fn my_test() {
function_from_main();
}
And cargo test -- --nocapture
runs the test as expected.
What's the most straightforward way to move this test into a separate file, (keeping function_from_main
in my_binary/src/main.rs
)?
I tried to do this but am not sure how to make my_test
call function_from_main
from a separate file.
The Rust Programming Language is a great resource for people learning about Rust. It covers many basic topics and many people have spent a lot of time working on it to improve it. Everyone interested in Rust should read it thoroughly.
It has an entire chapter dedicated to testing which you should cover for a baseline understanding.
It's common to put unit tests (tests that are more allowed to access internals of your code) into a
test
module in each specific file:Modules can be moved to new files, although this is uncommon for the unit test module:
main.rs
test.rs
The more common case for tests in a separate file are integration tests. These are also covered in the book by a section devoted to tests outside of the crate. These types of tests are well-suited for exercising the code as a consumer of your code would.
That section of the documentation includes an introductory example and descriptive text:
Note that the function is called as
adder::add_two
. Further details about Rust's module system can be found in the Packages, Crates, and Modules chapter.You're right;
function_from_main
is inaccessible outside ofmain.rs
.You need to create an
src/lib.rs
and move the functions you want to test piecemeal. Then you'll be able to useextern crate my_binary;
from your test module, and have your functions appear under themy_binary
namespace.