rust / expert
Snippet
Mocking Dependency Behavior with Thread-Local State
Mocking dependencies in multi-threaded test runners can lead to race conditions if global state is used. By leveraging thread-local storage (thread_local!), you can securely inject mock behaviors that only affect the current test thread, enabling safe parallel execution of unit tests with zero external testing dependencies.
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
29
30
31
32
33
34
35
36
37
38
39
use std::cell::RefCell;thread_local! {static MOCK_DB_RESPONSE: RefCell<Option<Result<String, &'static str>>> = const { RefCell::new(None) };}pub fn fetch_user_data(user_id: u32) -> Result<String, &'static str> {let mut mock_result = None;MOCK_DB_RESPONSE.with(|cell| {if let Some(ref res) = *cell.borrow() {mock_result = Some(res.clone());}});if let Some(result) = mock_result {result} else {Ok(format!("Real User Data for {}", user_id))}}#[cfg(test)]mod tests {use super::*;#[test]fn test_fetch_user_data_mocked() {MOCK_DB_RESPONSE.with(|cell| {*cell.borrow_mut() = Some(Err("Database Timeout"));});let result = fetch_user_data(42);assert_eq!(result, Err("Database Timeout"));MOCK_DB_RESPONSE.with(|cell| {*cell.borrow_mut() = None;});}}
Breakdown
1
thread_local! {
Declares a thread-local static variable that is isolated to each executing thread.
2
MOCK_DB_RESPONSE.with(|cell| {
Accesses the thread-local RefCell by passing a closure to the with() method.
3
assert_eq!(result, Err("Database Timeout"));
Verifies that the function dynamically intercepted the mock failure instead of running real logic.