Function wiremock::matchers::body_json_schema
source · pub fn body_json_schema<T>(request: &Request) -> boolwhere
for<'de> T: Deserialize<'de>,
Expand description
Match an incoming request if its body is encoded as JSON and can be deserialized according to the specified schema.
Example:
use wiremock::{MockServer, Mock, ResponseTemplate};
use wiremock::matchers::body_json_schema;
use serde_json::json;
use serde::{Deserialize, Serialize};
// The schema we expect the body to conform to.
#[derive(Deserialize, Serialize)]
struct Greeting {
hello: String,
}
#[async_std::main]
async fn main() {
// Arrange
let mock_server = MockServer::start().await;
Mock::given(body_json_schema::<Greeting>)
.respond_with(ResponseTemplate::new(200))
.mount(&mock_server)
.await;
// Both JSON objects have the same fields,
// therefore they'll match.
let success_cases = vec![
json!({"hello": "world!"}),
json!({"hello": "everyone!"}),
];
for case in success_cases.into_iter() {
let status = surf::post(&mock_server.uri())
.body(case)
.await
.unwrap()
.status();
// Assert
assert_eq!(status, 200);
}
// This JSON object cannot be deserialized as `Greeting`
// because it does not have the `hello` field.
// It won't match.
let failure_case = json!({"world": "hello!"});
let status = surf::post(&mock_server.uri())
.body(failure_case)
.await
.unwrap()
.status();
// Assert
assert_eq!(status, 404);
}