XUnitAssured.Http 6.31.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package XUnitAssured.Http --version 6.31.0
                    
NuGet\Install-Package XUnitAssured.Http -Version 6.31.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="XUnitAssured.Http" Version="6.31.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="XUnitAssured.Http" Version="6.31.0" />
                    
Directory.Packages.props
<PackageReference Include="XUnitAssured.Http" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add XUnitAssured.Http --version 6.31.0
                    
#r "nuget: XUnitAssured.Http, 6.31.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package XUnitAssured.Http@6.31.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=XUnitAssured.Http&version=6.31.0
                    
Install as a Cake Addin
#tool nuget:?package=XUnitAssured.Http&version=6.31.0
                    
Install as a Cake Tool

XUnitAssured.Http

HTTP/REST API testing extensions for the XUnitAssured.Net framework. Write expressive integration tests using a fluent Given() … ExecuteAsync() … Then() DSL with full support for HTTP methods, headers, authentication, JSON path assertions, and schema validation.

Installation

dotnet add package XUnitAssured.Http

Testing your own ASP.NET Core API? XUnitAssured.Http.AspNetCore hosts it in memory with a client per identity, shared across the suite.

Quick Start

using XUnitAssured.Http.Extensions;
using XUnitAssured.Http.Testing;

public class ProductTests : HttpTestBase<MyTestFixture>, IClassFixture<MyTestFixture>
{
    public ProductTests(MyTestFixture fixture) : base(fixture) { }

    [Fact]
    public async Task GetProduct_ShouldReturn200()
    {
        await Given()
            .ApiResource("/api/products/1")
            .Get()
            .ExecuteAsync()
            .AssertStatusCode(200)
            .AssertJsonPath<string>("$.name", name => name.ShouldNotBeEmpty())
            .AssertJsonPath<decimal>("$.price", price => price.ShouldBeGreaterThan(0));
    }
}

ExecuteAsync() sends the request, and the assertions chain right after it, with a single await at the start. A failed AssertStatusCode shows the response body, which is usually where the reason is. Await the whole chain: the request goes out either way, but without the await a failed assertion is never seen and the test passes.

The assertions can also wait for a result kept in a variable — var response = await ...ExecuteAsync(); then response.Then()... — or in parentheses, (await ...ExecuteAsync()).Then(). That is how to use Extract(out ...) and ExtractJsonPath(..., out ...), the two that cannot come before the await; to read a value in the chain, end it with JsonPath<T>("$.id") instead.

.Then() before the assertions and .When() before ExecuteAsync() are optional and change nothing: keep them only if you like the Given/When/Then reading. Execute(), the synchronous form, still exists so older suites keep compiling, but it blocks the test thread while it waits — write new tests with ExecuteAsync().

Fluent DSL Reference

Request Setup

Given()                                    // Given(client): every request of the scenario goes through client
    .ApiResource("/api/endpoint")          // Set target URL
    .WithHttpClient(client)                // Use a custom HttpClient for this request only
    .WithHeader("X-Custom", "value")       // Add request header
    .WithQueryParam("page", 1)             // Add query parameter
    .WithTimeout(30)                       // Set timeout in seconds

A URL from an earlier step

A chain is described first and run when it executes, so a string interpolated while writing it is built before any step has run. When the URL depends on a value an earlier step produces — the usual case is creating a resource and reading it back — pass a function, built when the step runs:

int productId = 0;

var readBack = await Given()
    .ApiResource("/api/products").Post(newProduct)
    .ExpectStatusCode(201)
    .Validate((HttpStepResult created) => productId = created.JsonPath<int>("$.id"))
    .And()
    .ApiResource(() => $"/api/products/{productId}").Get()
    .ExecuteAsync();

readBack.Then().AssertStatusCode(200);

A 201 alone proves the API answered; reading the resource back proves it was stored.

ExpectStatusCode checks the step it follows right after that step runs. When the creation gets another status, the scenario stops there, and the failure names the request and shows the body — After POST /api/products: Expected HTTP status code 201 but got 400. Body: ... — instead of a read-back of /api/products/0 failing for a reason that is not its own. It accepts several codes, like AssertStatusCode(403, 404). The last step is asserted after ExecuteAsync(), as always.

Arranging data

Creating a parent resource and keeping its id fits in one line. ExtractAsync runs the chain, requires a 2xx, and returns the value; a failed arrange fails right there, with the status and the body, instead of handing the test an empty id:

var customerId = await Given().ApiResource("/customers").Post(customer).ExtractAsync<string>("$.id");
var (id, token) = await Given().ApiResource(route).Post(invite).ExtractAsync<string, string>("$.id", "$.token");
await Given().ApiResource($"/orders/{id}").Delete().EnsureSuccessAsync();   // no value needed

HTTP Methods

.Get()                                     // HTTP GET
.Post(body)                                // HTTP POST with JSON body
.Post()                                    // HTTP POST without body
.PostFormData(formDictionary)              // POST form-urlencoded
.Put(body)                                 // HTTP PUT with JSON body
.Patch(body)                               // HTTP PATCH with JSON body
.Delete()                                  // HTTP DELETE
.PostRaw(text, "application/json")         // POST the text as written, no serialization
.PutRaw(text, contentType)                 // and PUT, PATCH: PatchRaw

The raw verbs are for what a serializer never produces: malformed JSON on purpose, a field of the wrong type, XML, plain text. The Content-Type goes as given, parameters included.

Assertions

await Given()
    .ApiResource("/api/products/1")
    .Get()
    .ExecuteAsync()
    .AssertStatusCode(200)                                              // the body is shown when it fails
    .AssertStatusCode(403, 404)                                         // any of these, e.g. access denied by design
    .AssertSuccess()                                                    // Assert IsValid = true
    .ValidateContract<Product>()                                        // Validate JSON schema against type
    .AssertJsonPath<int>("$.id", id => id.ShouldBe(1))                  // Assert JSON value with Shouldly
    .AssertJsonPath<string>("$.name", n => n.ShouldNotBeNullOrEmpty())   // Assert JSON string
    .Extract(r => myVar = r.StatusCode)                                 // Capture via callback
    .JsonPath<int>("$.id")                                              // Ends the chain with the value: var id = await ...

Null or missing

A field present with null and a field that is not there are different answers, and each has its own assertion. The failure says which of the two the response had:

.Then()
    .AssertJsonPathNull("$.contactId")                                  // "contactId": null
    .AssertJsonPathMissing("$.password")                                // no "password" at all

AssertJsonPathMissing needs everything before the last part of the path to exist. If an earlier part is missing too, the path is more likely wrong than the field absent, so the assertion fails.

Lists

A path can start at a root array ($[0].id), and [*] selects a value from every item ($[*].id, $.items[*].sku). A filter is only tested when the test proves what it left out:

.Then()
    .AssertJsonPathContains("$[*].id", matchingId)                      // must be in the result
    .AssertJsonPathNotContains("$[*].id", otherCityId)                  // must have been filtered out
    .AssertJsonPathCount("$.items", 2)                                  // array length, or values [*] selects
    .AssertJsonPathAll<string>("$[*].city", c => c == "Rio")           // every value; fails on an empty list
    .JsonPathAll<string>("$[*].id")                                     // extract every selected value

AssertJsonPathAll fails when the path selects nothing: an empty list satisfies any condition, so a search that returned nothing would otherwise pass.

To find one item of a list by a field, filter it in the path, and go on reading inside it:

.Then()
    .AssertJsonPath<string>("$.members[?(@.id=='" + memberId + "')].name", n => n == "Maria Silva")
    .AssertJsonPathNull("$.drafts[?(@.weekStart=='2026-10-12')].incomplete")
    .AssertJsonPathCount("$.drafts[?(@.published==false)]", 2)          // a filter at the end: how many match
    .AssertJsonPathCount("$.drafts[?(@.weekStart=='2026-10-12')].memberIds", 3) // in the middle: finds the item
  • The filter compares one field with == or !=, against a text in quotes, a number, true, false or null. @.a.b reads a nested field, and @ alone the item itself ($.tags[?(@=='rio')]).
  • Text and number do not mix: '1' is not 1. As in RFC 9535, != is the opposite of ==, so an item without the field is selected by !=.
  • Where one value is read (JsonPath<T>, AssertJsonPath, AssertJsonPathNull), the filter must match exactly one item. The error says how many it matched, out of how many. JsonPathAll and the list assertions take every match.

When the condition spans several fields of the same item, which a filter cannot combine, test the items whole with AssertJsonPathAny:

.AssertJsonPathAny<JsonElement>("$.items[*]", item =>
    item.GetProperty("action").GetInt32() == 1 &&
    item.GetProperty("changes").EnumerateArray().Any(c => c.GetProperty("field").GetString() == "Name"))

Headers, cookies, Problem Details and body text

.Then()
    .AssertHeader("Location", "/api/orders/42")                         // header names are case-insensitive
    .AssertNoHeader("X-Powered-By")
    .AssertSetCookie("session", c => c.HttpOnly && c.Secure && c.Path == "/auth")
    .AssertCookieCleared("session")                                     // expiry in the past or Max-Age=0
    .AssertProblemDetails(409, p => p.Extension<string>("code") == "ScheduleConflict")
    .AssertBodyContains("not found")
    .AssertBodyNotContains("invited@example.com")                       // the response must not leak it

AssertCookieCleared reads the expiry: checking that the header text mentions expires= is not the same thing, since a date in the future mentions it too.

To use a cookie the response set, for example to replay a session from another client, read it from the result. SetCookie returns null when the response did not set it:

var signIn = await Given().ApiResource("/auth/login").Post(credentials).ExecuteAsync().GetResult();
var session = signIn.SetCookie("sid")!.Value;                           // attributes too: .HttpOnly, .Path, .Expires

The request that was sent

result.Request is the request as it went out, read after the client sent it: method, address, headers, cookies and body. It includes what the client added on the way — a client that keeps cookies puts the session in the Cookie header, and that is what a session test is about:

using var browser = api.ClientWithCookies();
// ... sign in, then sign out ...

await Given(browser)
    .ApiResource("/auth/refresh")
    .Post()
    .ExecuteAsync()
    .AssertStatusCode(401)
    .AssertNoSentCookie("refresh")                                      // the revoked session is gone
    .AssertRequestHeader("X-Correlation-Id", id => id.Length > 0);     // names are case-insensitive

AssertSentCookie("name", v => ...) requires the cookie, and optionally checks its value.

Requests at once

For a test whose subject is the concurrency itself — simultaneous creates under one parent, a double submit, a race on a counter — Concurrently sends the request several times at once, through the same client. Every copy is started before any is awaited.

var names = Enumerable.Range(1, 6).Select(i => $"Member {i}").ToList();

await Given()
    .ApiResource($"/api/teams/{teamId}/members")
    .Post()
    .Concurrently(names.Select(n => new { Name = n }))                  // one request per body
    .ExecuteAsync()
    .AssertStatusCode(201)                                              // every one of the six
    .AssertEach(r => r.AssertHeader("Location", l => l.StartsWith("/api/members/")));

Concurrently(3) sends the same body three times. The result is a ConcurrentHttpStepResult: its Responses come in the order of the bodies, AssertStatusCode checks all of them and lists every code when one differs, and AssertEach runs any other assertion on each response, naming the ones that failed. An assertion about a single body or header on it says to use AssertEach instead.

What the system did besides answering

Some of the most valuable E2E tests are about side effects: what the system logged, and which outside services it called.

Logs: LogCapture

using XUnitAssured.Core.Logging;

var logs = new LogCapture();
var app = new WebApplicationFactory<Program>().WithWebHostBuilder(b =>
    b.ConfigureLogging(log => { log.SetMinimumLevel(LogLevel.Trace); log.AddProvider(logs); }));

logs.Clear();                                                   // only what the action below logs
// ... the request under test ...
logs.AssertLoggedOnce("MyApp.Errors", LogLevel.Error)           // one error, not three
    .AssertLogged("MyApp.Security", LogLevel.Warning, e => e.EventId.Id == 9001)
    .AssertNothingContains(patientName);                        // message, exception, values and scopes

AssertNothingContains looks at everything an entry carries — the message, the exception with its stack trace, the structured values and the active scopes — since a value kept out of the message can still ride in a scope.

Outbound calls: OutboundHttpCapture

Stands in for an outside service at the HTTP boundary: it answers what the test configures and records every request. Replacing the component that calls the service would hide the logic under test; here everything up to the request itself runs for real.

using XUnitAssured.Http.Testing;

var push = new OutboundHttpCapture()
    .RespondWith(HttpStatusCode.Created)
    .When("https://push.example/devices/gone*", HttpStatusCode.Gone);

// in ConfigureTestServices:
services.AddHttpClient("push").ConfigurePrimaryHttpMessageHandler(() => push);

// ... the request under test ...
push.AssertSent("https://push.example/devices/*", times: 2)
    .AssertSent("https://push.example/*", predicate: r => r.BodyText.Contains("\"lang\":\"es\""))
    .AssertNotSent("https://push.example/devices/removed*");

* stands for any run of characters. It keeps working after a client that owns it is disposed, so IHttpClientFactory recycling handlers does not break it mid-test.

Authentication

Bearer Token

await Given()
    .ApiResource("/api/secure")
    .WithBearerToken("my-jwt-token")
    .Get()
    .ExecuteAsync()
    .AssertStatusCode(200);

Basic Auth

await Given()
    .ApiResource("/api/secure")
    .WithBasicAuth("username", "password")
    .Get()
    .ExecuteAsync()
    .AssertStatusCode(200);

API Key

// Header
await Given()
    .ApiResource("/api/secure")
    .WithApiKey("X-API-Key", "my-key")
    .Get()
    .ExecuteAsync()
    .AssertStatusCode(200);

// Query string
await Given()
    .ApiResource("/api/secure")
    .WithApiKey("api_key", "my-key", ApiKeyLocation.Query)
    .Get()
    .ExecuteAsync()
    .AssertStatusCode(200);

OAuth2 Client Credentials

await Given()
    .ApiResource("/api/secure")
    .WithOAuth2("https://auth.example.com/token", "client-id", "client-secret")
    .Get()
    .ExecuteAsync()
    .AssertStatusCode(200);

Certificate (mTLS)

await Given()
    .ApiResource("/api/secure")
    .WithCertificate("client.pfx", "password")
    .Get()
    .ExecuteAsync()
    .AssertStatusCode(200);

Custom Header Auth

await Given()
    .ApiResource("/api/secure")
    .WithAuthConfig(config => config.UseCustomHeader("X-Auth-Token", "my-token"))
    .Get()
    .ExecuteAsync()
    .AssertStatusCode(200);

Automatic Authentication via testsettings.json

Configure authentication once and have it applied to every request automatically:

{
  "testMode": "Remote",
  "http": {
    "baseUrl": "https://api.example.com",
    "timeout": 60,
    "authentication": {
      "type": "Bearer",
      "bearer": {
        "token": "your-jwt-token"
      }
    }
  }
}

Implement IHttpClientAuthProvider in your fixture:

public class MyFixture : IHttpClientProvider, IHttpClientAuthProvider, IDisposable
{
    private readonly HttpSettings _settings;
    private readonly HttpClient _client;

    public MyFixture()
    {
        var settings = TestSettings.Load();
        _settings = settings.GetHttpSettings()!;
        _client = new HttpClient { BaseAddress = new Uri(_settings.BaseUrl) };
    }

    public HttpClient CreateClient() => _client;
    public HttpAuthConfig? GetAuthenticationConfig() => _settings.Authentication;

    public void Dispose() => _client?.Dispose();
}

Then use Given(fixture) — auth is applied automatically:

await Given(fixture)
    .ApiResource("/api/products")
    .Get()
    .ExecuteAsync()
    .AssertStatusCode(200);

CRUD Example

// GET all
await Given()
    .ApiResource("/api/products")
    .Get()
    .ExecuteAsync()
    .AssertStatusCode(200);

// GET by ID
await Given()
    .ApiResource("/api/products/1")
    .Get()
    .ExecuteAsync()
    .AssertStatusCode(200)
    .AssertJsonPath<int>("$.id", id => id.ShouldBe(1));

// POST create
await Given()
    .ApiResource("/api/products")
    .Post(new { name = "Laptop", price = 999.99m })
    .ExecuteAsync()
    .AssertStatusCode(201)
    .AssertJsonPath<int>("$.id", id => id.ShouldBeGreaterThan(0));

// PUT update
await Given()
    .ApiResource("/api/products/1")
    .Put(new { name = "Updated Laptop", price = 899.99m })
    .ExecuteAsync()
    .AssertStatusCode(200);

// DELETE
await Given()
    .ApiResource("/api/products/1")
    .Delete()
    .ExecuteAsync()
    .AssertStatusCode(204);

Local Testing with WebApplicationFactory

To test your own ASP.NET Core API in memory, use XUnitAssured.Http.AspNetCore: ApiFixture<Program> hosts it with WebApplicationFactory, gives Given() its client, and adds a client per identity, clients with and without cookies, its services and its logs.

public sealed class MyApi : ApiFixture<Program>
{
    protected override void ConfigureApi(IWebHostBuilder api) => api.UseEnvironment("Testing");
}

[CollectionDefinition("API")]
public sealed class ApiCollection : ICollectionFixture<MyApi>;

[Collection("API")]
public class LocalTests(MyApi api) : HttpTestBase<MyApi>(api)
{
    [Fact]
    public async Task GetProducts_ShouldReturn200() =>
        await Given()
            .ApiResource("/api/products")
            .Get()
            .ExecuteAsync()
            .AssertStatusCode(200);
}

Supported Frameworks

  • .NET 8
  • .NET 9
  • .NET 10

Dependencies

License

Apache-2.0 — see LICENSE.md

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on XUnitAssured.Http:

Package Downloads
XUnitAssured.Http.AspNetCore

HTTP tests against your own ASP.NET Core API with XUnitAssured.Http: ApiFixture hosts the API in memory with WebApplicationFactory and hands out a shared client, a new client per identity, clients with and without cookies, the API's services and its logs — one instance for the whole suite through a collection fixture.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
6.43.0 114 11/7/2026
6.42.0 115 11/6/2026
6.41.0 115 11/6/2026
6.40.0 108 11/6/2026
6.39.0 110 11/6/2026
6.38.0 112 11/5/2026
6.37.1 110 11/5/2026
6.37.0 113 11/5/2026
6.36.1 125 10/29/2026
6.36.0 152 10/18/2026
6.35.0 126 10/18/2026
6.34.0 119 10/18/2026
6.33.0 134 10/18/2026
6.32.0 122 10/17/2026
6.31.5 122 10/17/2026
6.31.4 113 10/17/2026
6.31.3 116 10/17/2026
6.31.2 123 10/17/2026
6.31.1 122 10/17/2026
6.31.0 112 10/16/2026
Loading failed

New package XUnitAssured.Camunda: deploy BPMN, start real Camunda 8.10 process instances on a shared cluster and mock the diagram's job workers per instance, with assertions that wait for the cluster. The other packages are unchanged from 6.19.1. Upgrade guide: https://github.com/andrewBezerra/xunit-assured-net/blob/main/UPGRADING.md