|
| 1 | +# Mock Builder |
| 2 | + |
| 3 | +"Mock builder" refers to a closure with `When` and `Then` parameters used to build the request match conditions and response, respectively. |
| 4 | + |
| 5 | +```rust |
| 6 | + // A mock that returns the text "yo!" to any request |
| 7 | + let mock = Mock::new(|when, then| { |
| 8 | + when.any(); // builds a set of request match conditions |
| 9 | + then.text("yo!"); // builds the response to return when conditions are matched |
| 10 | + }) |
| 11 | +``` |
| 12 | + |
| 13 | +Together, they build a `Mock`, which consists of a set of request match conditions, a response, and a priority: |
| 14 | + |
| 15 | +```rust |
| 16 | +pub struct Mock { |
| 17 | + /// A set of request match conditions. |
| 18 | + pub matchers: Vec<Box<dyn Matcher>>, |
| 19 | + /// A mock response. |
| 20 | + pub response: Response, |
| 21 | + /// Priority. |
| 22 | + pub priority: u8, // defaults to 5 (more on this later) |
| 23 | +} |
| 24 | +``` |
| 25 | + |
| 26 | +Since `when` and `then` are just variables of types `When` and `Then`, you can name them however you'd like, e.g. the following also works. |
| 27 | + |
| 28 | +```rust |
| 29 | + // A mock that returns the text "index" to get requests on the / endpoint |
| 30 | + let mock = Mock::new(|req, res| { |
| 31 | + req.get().path("/"); |
| 32 | + res.text("index"); |
| 33 | + }) |
| 34 | +``` |
| 35 | + |
| 36 | +We experimented with several different APIs and found this closure-builder pattern to feel the most ergonomic and nice to use. |
| 37 | + |
| 38 | +The mock builder closure is exposed via 3 methods, allowing flexible usage patterns: |
| 39 | + |
| 40 | +1. `Mock::new(|when, then|...)` to build a standalone mock |
| 41 | +2. `MockSet::mock(|when, then|...)` shorthand to build a mock and insert it into the mock set |
| 42 | +3. `MockServer::mock(|when, then|...)` shorthand to build a mock and insert it into the server's mock set |
0 commit comments