-
Notifications
You must be signed in to change notification settings - Fork 4
Matching a request
Martijn Bodeman edited this page Sep 7, 2024
·
11 revisions
MockHttp provides a fluent API to make setting up request expectations and verifications easy.
Create the handler and then start configuring a request:
var mockHttp = new MockHttpHandler();
mockHttp
.When(matching => matching
// Start chaining request expectations
.Method(...)
.RequestUri(...)
// etc...
)
...
Configure multiple requests on the same handler as needed.
Method | Description |
---|---|
matching.Method("POST") matching.Method(HttpMethod.Post) |
Matches the HTTP method. |
matching.RequestUri("http://localhost/exact/match?query=string") matching.RequestUri("*/match*") |
Matches an url. Accepts wildcard * . |
.QueryString("key", "value") |
Matches a query string by one or more key/value pairs. Note: the overload that accepts a full query string must be URI data escaped. |
.WithoutQueryString() |
Matches a request without query string. |
.Body("text content") |
Matches the request content body. |
.JsonBody(new { name = "John" }) // Defaults to STJ. |
Matches the request content body as JSON. Requires 'skwas.MockHttp.Json' package |
.WithoutBody() |
Matches a request without content. |
.PartialBody("text content") |
Matches the content body partially. |
.ContentType("application/json; charset=utf-8") |
Matches the request content type. |
.Header("Authorization", "Bearer 123") |
Matches request headers by one or more key/value pairs. |
.FormData("key", "value") |
Matches form url encoded or multipart encoded form data by one or more key/value pairs. Note: the overload that accepts a string must be URI data escaped. |
.Any(any => any |
Matches when at least one of the inner configured conditions is true. |
.Where(request => true|false) |
Matches the request using a custom predicate/expression. |
.Version("2.0") |
Matches the request by HTTP message version. |
Sometimes you have to just assert that something is NOT in the request. In such case use the .Not
Fluent operator:
var mockHttp = new MockHttpHandler();
mockHttp
// Match all requests without Authorization header
.When(m => m.Not.Header("Authorization"))
.Respond(with => with.StatusCode(HttpStatusCode.Unauthorized));
Note: this is new in v2.4.x