Testing the API
Integration tests.
Why Test an API?
Tests give you confidence that endpoints behave correctly and keep working as you change code. For a REST API the most valuable tests are integration tests: they exercise the real router end to end, sending requests and asserting on responses.
This lesson covers unit tests, the Tower oneshot trick, and full integration tests.
Unit Tests for Pure Logic
Logic that does not touch the network, such as validation, can be tested with plain Rust unit tests. Put them in a #[cfg(test)] module beside the code. These run fast with cargo test.
fn validate_title(title: &str) -> bool {
!title.trim().is_empty()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rejects_empty() {
assert!(!validate_title(" "));
assert!(validate_title("buy milk"));
}
}All lessons in this course
- Project Setup
- Endpoints and Models
- Database Integration
- Testing the API