-
-
Notifications
You must be signed in to change notification settings - Fork 114
Description
Problem
Integration tests almost universally need HTTP response assertions. Currently users must create their own via [GenerateAssertion]:
// Every integration test project needs to write these
public static partial class HttpAssertionExtensions
{
[GenerateAssertion(ExpectationMessage = "have status code 201 Created")]
public static bool IsCreated(this HttpResponseMessage response)
=> response.StatusCode == HttpStatusCode.Created;
[GenerateAssertion(ExpectationMessage = "have status code 400 Bad Request")]
public static bool IsBadRequest(this HttpResponseMessage response)
=> response.StatusCode == HttpStatusCode.BadRequest;
// ... IsNotFound, IsForbidden, IsUnauthorized, HasJsonContent, HasStatusCode, etc.
}In the CloudShop example, 7 custom assertions were needed just for HTTP responses. Every API test project would need the same ones.
Proposal
Since HttpResponseMessage is part of the .NET base class library (not an external dependency), these assertions should be included directly in TUnit.Assertions — no separate package needed.
Status Code Assertions
// Specific status codes
await Assert.That(response).IsOk(); // 200
await Assert.That(response).IsCreated(); // 201
await Assert.That(response).IsNoContent(); // 204
await Assert.That(response).IsBadRequest(); // 400
await Assert.That(response).IsUnauthorized(); // 401
await Assert.That(response).IsForbidden(); // 403
await Assert.That(response).IsNotFound(); // 404
await Assert.That(response).IsConflict(); // 409
// General
await Assert.That(response).HasStatusCode(HttpStatusCode.TooManyRequests);
await Assert.That(response).IsSuccessStatusCode(); // 2xx
await Assert.That(response).IsRedirectStatusCode(); // 3xx
await Assert.That(response).IsClientErrorStatusCode(); // 4xx
await Assert.That(response).IsServerErrorStatusCode(); // 5xxContent Assertions
await Assert.That(response).HasJsonContent();
await Assert.That(response).HasContentType("text/html");Header Assertions
await Assert.That(response).HasHeader("X-Request-Id");
await Assert.That(response).HasHeader("Location").ContainingValue("/api/products/1");Implementation
These can be implemented using [GenerateAssertion] within TUnit.Assertions itself, keeping them consistent with the rest of the assertion library. Since System.Net.Http is part of the BCL, there are no additional package dependencies required.
Context
Discovered while building the CloudShop Aspire + TUnit example (#4761). These assertions were needed in nearly every test class.