2023-11-29 10:39:24 -05:00
|
|
|
---
|
2024-02-06 15:48:56 -05:00
|
|
|
minutes: 5
|
2023-11-29 10:39:24 -05:00
|
|
|
---
|
|
|
|
|
|
|
|
# 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/`:
|
|
|
|
|
|
|
|
```rust,ignore
|
|
|
|
// tests/my_library.rs
|
|
|
|
use my_library::init;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_init() {
|
|
|
|
assert!(init().is_ok());
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
These tests only have access to the public API of your crate.
|
|
|
|
|
|
|
|
## Documentation Tests
|
2022-12-21 16:36:30 +01:00
|
|
|
|
|
|
|
Rust has built-in support for documentation tests:
|
|
|
|
|
2023-12-31 00:15:07 +01:00
|
|
|
````rust
|
2023-01-17 12:33:50 +00:00
|
|
|
/// Shortens a string to the given length.
|
2022-12-21 16:36:30 +01:00
|
|
|
///
|
|
|
|
/// ```
|
2023-10-02 08:23:46 -04:00
|
|
|
/// # use playground::shorten_string;
|
2022-12-21 16:36:30 +01:00
|
|
|
/// assert_eq!(shorten_string("Hello World", 5), "Hello");
|
|
|
|
/// assert_eq!(shorten_string("Hello World", 20), "Hello World");
|
|
|
|
/// ```
|
|
|
|
pub fn shorten_string(s: &str, length: usize) -> &str {
|
|
|
|
&s[..std::cmp::min(length, s.len())]
|
|
|
|
}
|
2023-12-31 00:15:07 +01:00
|
|
|
````
|
|
|
|
|
|
|
|
- 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](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=3ce2ad13ea1302f6572cb15cd96becf0).
|