-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmocks.rs
More file actions
58 lines (47 loc) · 1.38 KB
/
Copy pathmocks.rs
File metadata and controls
58 lines (47 loc) · 1.38 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
This example shows the idiomatic Rust way to replace Mockito-style mocks.
`UserService` does not depend on a concrete database implementation.
It depends on the `UserRepo` trait, so production code can use `OracleRepo`
and tests can provide a small `MockUserRepo`.
The mock is just another struct implementing the same trait. No external mocking
framework is required for this simple case.
*/
trait UserRepo {
fn find_user_by_id(&self, id: &str) -> String;
}
struct UserService<T:UserRepo> {
user_repo: T,
}
impl<T: UserRepo> UserService<T> {
fn find(&self, id:&str) -> String {
self.user_repo.find_user_by_id(id)
}
}
struct OracleRepo;
impl UserRepo for OracleRepo {
fn find_user_by_id(&self, id:&str) -> String {
//Find in DB
"real_user".to_string()
}
}
mod test {
use super::*;
#[test]
fn dev_user_repo() {
struct MockUserRepo;
impl UserRepo for MockUserRepo {
fn find_user_by_id(&self, id: &str) -> String {
String::from("Politrons")
}
}
let service = UserService {user_repo:MockUserRepo};
let user = service.find("foo");
println!("User found {}",user);
}
#[test]
fn prod_user_repo() {
let service = UserService {user_repo:OracleRepo};
let user = service.find("foo");
println!("User found {}",user);
}
}