Other Types of Tests

Integration Tests

If you want to test your library as a client, use an integration test.

Create a .rs file under tests/:

  1. // tests/my_library.rs
  2. use my_library::init;
  3. #[test]
  4. fn test_init() {
  5. assert!(init().is_ok());
  6. }

These tests only have access to the public API of your crate.

Documentation Tests

Rust has built-in support for documentation tests:

  1. #![allow(unused)]
  2. fn main() {
  3. /// Shortens a string to the given length.
  4. ///
  5. /// ```
  6. /// # use playground::shorten_string;
  7. /// assert_eq!(shorten_string("Hello World", 5), "Hello");
  8. /// assert_eq!(shorten_string("Hello World", 20), "Hello World");
  9. /// ```
  10. pub fn shorten_string(s: &str, length: usize) -> &str {
  11.     &s[..std::cmp::min(length, s.len())]
  12. }
  13. }
  • Code blocks in /// comments are automatically seen as Rust code.
  • The code will be compiled and executed as part of cargo test.
  • Adding # in the code will hide it from the docs, but will still compile/run it.
  • Test the above code on the Rust Playground.