Skip to content

Matching a request

skwasjer edited this page Jan 31, 2020 · 11 revisions

MockHttp provides a fluent API to make setting up request expectations and verifications easy.

Example

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.

Fluent API methods

Method Description
.Method("POST")
.Method(HttpMethod.Put)
Matches the request method.
.RequestUri("http://localhost/exact/match?query=string")
.RequestUri("*/match*")
Matches an url. Accepts wildcard *.
.QueryString("key", "value")
.QueryString("?key=value1&other=value&key=value2")
.QueryString(new Dictionary<string, string>
{
{ "key", "value" }
}
.QueryString(new NameValueCollection
{
{ "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.
.Content("text content")
.Content("text content", Encoding.UTF8)
.Content(stream)
.Content(byteArray)
Matches the request content body.
.JsonContent(new { name = "John" })
.JsonContent(
new { name = "John" },
new JsonSerializerSettings()
)
Matches the request content body as JSON.
Requires 'skwas.MockHttp.Json' package
.WithoutContent()
Matches a request without content.
.PartialContent("text content")
.PartialContent("text content", Encoding.UTF8)
.PartialContent(byteArray)
Matches the content body partially.
.ContentType("application/json; charset=utf-8")
.ContentType("text/plain", Encoding.ASCII)
Matches the request content type.
.Header("Authorization", "Bearer 123")
.Header("Content-Length", 123)
.Header("Last-Modified", DateTime.UtcNow)
.Headers("Accept: text/html")
.Headers(new Dictionary<string, string>
{
{ "Authorization", "Bearer 123" }
})
Matches request headers by one or more key/value pairs.
.FormData("key", "value")
.FormData("key=value1&other=value&key=value2")
.FormData(new Dictionary<string, string>
{
{ "key", "value" }
}
.FormData(new NameValueCollection
{
{ "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
.Method("GET")
.Method("POST")
)
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")
.Version(new Version(1, 1))
Matches the request by HTTP message version.
Clone this wiki locally