rust / expert
Snippet
Decoupling External Resources in Unit Testing using Mock Traits
In unit testing, decoupling business logic from external components is essential. By abstracting interfaces into traits, mock implementations can simulate varying conditions, such as connection errors or edge cases, ensuring robust test coverage without invoking live network or database services.
snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
pub trait Transceiver {fn send_payload(&self, data: &[u8]) -> Result<(), &'static str>;}pub struct MockTransceiver {pub force_failure: bool,}impl Transceiver for MockTransceiver {fn send_payload(&self, data: &[u8]) -> Result<(), &'static str> {if self.force_failure || data.is_empty() {Err("Network failure simulation")} else {Ok(())}}}#[cfg(test)]mod tests {use super::*;#[test]fn test_payload_handling() {let mock = MockTransceiver { force_failure: true };assert!(mock.send_payload(b"hello").is_err());}}
Breakdown
1
pub trait Transceiver {
Declares a trait representing standard messaging behaviors to isolate network side-effects.
2
pub struct MockTransceiver {
Defines a mock structure with configuration parameters to control test outcomes manually.
3
#[cfg(test)]
Ensures the following module is compiled and executed exclusively when running cargo test commands.