Skip to content

Commit c118f35

Browse files
committed
Update README.md
Signed-off-by: declark1 <[email protected]>
1 parent c3ecacb commit c118f35

File tree

1 file changed

+59
-1
lines changed

1 file changed

+59
-1
lines changed

README.md

+59-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,65 @@ mocktail is a **minimal** crate for mocking HTTP and gRPC servers in Rust, with
2828
mocktail = { git = "https://github.com/IBM/mocktail.git", version = "0.2.4-alpha" }
2929
```
3030

31-
2. For now, see [examples](/mocktail-tests/tests/examples) in the `mocktail-tests` crate. Additional documentation coming soon.
31+
2. Basic usage example:
32+
```rust
33+
use mocktail::prelude::*;
34+
35+
#[tokio::test]
36+
async fn test_example() -> Result<(), Box<dyn std::error::Error>> {
37+
// Create a mock set
38+
let mut mocks = MockSet::new();
39+
40+
// Build a mock that returns a "hello world!" response
41+
// to POST requests to the /hello endpoint with the text "world"
42+
// in the body.
43+
mocks.mock(|when, then| {
44+
when.post().path("/hello").text("world");
45+
then.text("hello world!");
46+
});
47+
48+
// Create and start a mock server
49+
let mut server = MockServer::new("example").with_mocks(mocks);
50+
server.start().await?;
51+
52+
// Create a client
53+
let client = reqwest::Client::builder().http2_prior_knowledge().build()?;
54+
55+
// Send a request that matches the mock created above
56+
let response = client
57+
.post(server.url("/hello"))
58+
.body("world")
59+
.send()
60+
.await?;
61+
assert_eq!(response.status(), http::StatusCode::OK);
62+
let body = response.text().await?;
63+
assert_eq!(body, "hello world!");
64+
65+
// Send a request that doesn't match a mock
66+
let response = client.get(server.url("/nope")).send().await?;
67+
assert_eq!(response.status(), http::StatusCode::NOT_FOUND);
68+
69+
// Mocks can also be registered to the server directly
70+
// Register a mock that will match the request above that returned 404
71+
server.mock(|when, then| {
72+
when.get().path("/nope");
73+
then.text("yep!");
74+
});
75+
76+
// Send the request again, it should now match
77+
let response = client.get(server.url("/nope")).send().await?;
78+
assert_eq!(response.status(), http::StatusCode::OK);
79+
let body = response.text().await?;
80+
assert_eq!(body, "yep!");
81+
82+
// Mocks can be cleared from the server, enabling server reuse
83+
server.mocks.clear();
84+
85+
Ok(())
86+
}
87+
```
88+
89+
3. See the [book](https://ibm.github.io/mocktail/) and [examples](/mocktail-tests/tests/examples) in the `mocktail-tests` crate.
3290

3391
# Examples
3492
See [examples](/mocktail-tests/tests/examples) in the `mocktail-tests` crate.

0 commit comments

Comments
 (0)