Follow these steps to learn more about creating a test suite for your Rust projects:
Once created, a library project already contains a very simple test (probably to encourage you to write more). The cfg(test) and test attributes tell cargo (the test runner) how to deal with the module:
Before we add further tests, let's add a subject that needs testing. In this case, let's use something interesting: a singly linked list from our other book (Hands-On Data Structures and Algorithms with Rust) made generic. It consists of three parts. First is a node type:
It's also a good idea to have an integration test that tests the library from end to end. For that, Rust offers a special folder in the project called tests, which can house additional tests that treat the library as a black box. Create and open the tests/list_integration.rsfile to add a test that inserts 10,000 items into our list:
use testing::List;
#[test] fn test_list_insert_10k_items() { let mut list = List::new_empty(); for _ in 0..10_000 { list.append(100); } assert_eq!(list.length, 10_000); }
Great, now each function has one test. Try it out by running cargo +nightly test in the testing/ root directory. The result should look like this:
$ cargo test Compiling testing v0.1.0 (Rust-Cookbook/Chapter01/testing) Finished dev [unoptimized + debuginfo] target(s) in 0.93s Running target/debug/deps/testing-a0355a7fb781369f
running 4 tests test tests::test_list_new_empty ... ok test tests::test_list_pop ... ok test tests::test_list_append ... ok test tests::bench_list_append ... ok
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out