HTTP Tests
- Introduction
- Complete Example: Escaped User Content
- Making Requests
- Authentication
- Response Assertions
- Fakes and HTTP Tests
- Testing Live Components
Introduction
HTTP tests send real requests to your application, running in memory, and check the responses. Every route, middleware, controller, validation rule, and view runs exactly as in production. Set up a TestApp fixture first.
[Fact]
public async Task Guests_are_redirected_to_login()
{
var response = await app.Client().Get("/posts/create");
response.AssertRedirect("/login");
}Making Requests
app.Client() is a new browser: it keeps its own cookies between requests (so a login carries over) and does not follow redirects, so tests can assert on them. Requests return a TestResponse:
var client = app.Client();
await client.Get("/posts");
await client.Post("/posts", new { Title = "Hello", Body = "World" });
await client.Put($"/posts/{id}", new { Title = "Changed" });
await client.Patch($"/posts/{id}", new { Title = "Changed" });
await client.Delete($"/posts/{id}");Send extra headers with WithHeader(name, value) or WithHeaders(...). client.Http is the underlying HttpClient, for anything not wrapped.
Forms and CSRF Tokens
Post, Put, Patch, and Delete send their data as form fields (an anonymous object or a dictionary), like an HTML form. The client adds a valid CSRF token to every one of them, so you never handle tokens. To test the 419 a request without a token gets:
(await app.Client().WithoutCsrfToken().Post("/posts", new { Title = "x" })).AssertStatus(419);JSON Requests
GetJson, PostJson, PutJson, PatchJson, and DeleteJson send a JSON body and Accept: application/json, like an API client or a fetch call. DotBlaze then answers validation errors with 422 and JSON instead of a redirect:
var response = await app.Client().ActingAs(user).PostJson("/posts", new { Title = "" });
response.AssertUnprocessable().AssertJsonValidationErrors("Title", "Body");AcceptJson() sends Accept: application/json with every request of the client.
File Uploads
await client.Upload("/avatar", new { Caption = "Me" }, ("Avatar", "me.png", File.ReadAllBytes("me.png")));Following Redirects
FollowingRedirects() makes the client follow redirects (with GET), so the response is the final page. It applies to every later request of that client:
(await app.Client().ActingAs(user).FollowingRedirects().Post("/posts", data)).AssertOk().AssertSee("Post created.");Authentication
ActingAs(user) logs the client in as a saved user before its next request, like Laravel's actingAs. The login is a real login cookie, so every middleware and Auth.User() see that user:
var user = await app.Run(() => User.Factory().Create());
(await app.Client().ActingAs(user).Get("/posts/create")).AssertOk();
var unverified = await app.Run(() => User.Factory<UserFactory>().Unverified().Create());
(await app.Client().ActingAs(unverified).Get("/posts")).AssertRedirectToRoute("verification.notice");Response Assertions
Every assertion returns the response, so they chain, and throws an AssertionFailedException with a readable message when it fails. Status, Body, Location, Json(), Json<T>(), and Response (the HttpResponseMessage) are available for your own checks; Dump() prints the response.
Status
AssertStatus(code), AssertOk(), AssertCreated(), AssertNoContent(), AssertBadRequest(), AssertUnauthorized(), AssertForbidden(), AssertNotFound(), AssertMethodNotAllowed(), AssertUnprocessable(), AssertTooManyRequests(), AssertSuccessful() (2xx), AssertServerError() (5xx).
Redirects
response.AssertRedirect(); // any redirect
response.AssertRedirect("/posts/5"); // path and query (an absolute URL is compared by path)
response.AssertRedirectToRoute("posts.show", new { post = 5 });
response.AssertRedirectContains("/posts/");Content
response.AssertSee("Ali's post"); // HTML-encoded like Razor output: matches "Ali's post"
response.AssertSee("<h1>", escape: false);
response.AssertDontSee("Draft");
response.AssertSeeText("Welcome back"); // the text without tags
response.AssertDontSeeText("Error");
response.AssertSeeInOrder("First", "Second", "Third");JSON
var response = await app.Client().GetJson("/api/posts");
response.AssertOk()
.AssertJson(new { currentPage = 1 }) // a subset: other properties may exist
.AssertJsonPath("items.0.title", "Hello") // dotted path, array indexes as numbers
.AssertJsonCount(1, "items")
.AssertJsonMissingPath("items.0.password");Property names are compared case-insensitively, and AssertJson serializes the expected object with camelCase names, like DotBlaze's responses.
Validation Errors, Flash Data, and Old Input
A form that fails validation redirects back with the errors and the old input in the flash data, which the response can read:
(await client.Post("/posts", new { Title = "", Body = "Kept" }))
.AssertRedirect()
.AssertSessionHasErrors("Title") // or AssertInvalid("Title")
.AssertValid("Body")
.AssertOldInput("Body", "Kept");
(await client.Post("/posts", new { Title = "Ok", Body = "Ok" }))
.AssertSessionHasNoErrors()
.AssertSessionHas("status", "Post created."); // a value flashed with .With("status", ...)AssertInvalid and AssertValid also read the errors of a 422 JSON response; Errors() returns the messages by field, and Session all flash data.
Headers and Cookies
AssertHeader(name, value?), AssertHeaderMissing(name), AssertCookie(name), AssertCookieMissing(name):
(await app.Client().GetJson("/api/posts")).AssertHeader("X-RateLimit-Limit", "60");Fakes and HTTP Tests
A fake made in the test also applies inside the requests the test sends, because TestApp runs requests in the test's execution context:
[Fact]
public async Task Publishing_notifies_the_author()
{
var notifications = Notification.Fake();
var user = await app.Run(() => User.Factory().Create());
await app.Client().ActingAs(user).Post("/posts", new { Title = "Hello", Body = "World" });
notifications.AssertSentTo<PostPublished>(user);
}Testing Live Components
client.Live(page, name) reads a live component from a page and drives it like the browser does:
var form = await app.Client().ActingAs(user).Live("/posts/create", "post-form");
await form.Call("Save");
form.AssertHasErrors("Title", "Body");
await form.Set(new { Title = "Live", Body = "Written in a test" });
await form.Call("Save");
form.AssertHasNoErrors().AssertRedirect();| Member | |
|---|---|
Call(method, args...) | Call an action, like live:click. |
Set(new { ... }) | Set properties, like live:model, and re-render. |
Send(updates, calls...) | Both in one request. |
Upload(fileName, bytes, contentType) | Upload a file; returns the token to Set on a LiveFile property. |
AssertSet(property, value), AssertSee(text), AssertDontSee(text) | State and rendered HTML. |
AssertHasErrors(fields...), AssertHasNoErrors() | Validation errors. |
AssertRedirect(uri?), AssertDispatched(event), AssertStatus(code) | Effects of the last update. |
Data, Html, Effects, Status | The raw state, HTML, and effects. |
Complete Example: Escaped User Content
Use the complete Blog application and test project. This verifies the actual controller and compiled Blade view:
// Blog.Tests/EscapedPostTest.cs
using Blog.Models;
using DotBlaze.Testing;
using Xunit;
namespace Blog.Tests;
public class EscapedPostTest
{
[Fact]
public async Task Post_body_is_rendered_as_text()
{
using var app = new TestApp<Program>();
await app.RefreshDatabase();
var user = await app.Run(() => User.Factory().Create());
var client = app.Client().ActingAs(user);
const string body = "<script>alert(1)</script>";
(await client.Post("/posts", new { Title = "Encoding example", Body = body }))
.AssertRedirect();
var post = await app.Run(() => Post.Where(value => value.Title == "Encoding example").FirstOrFail());
(await client.Get($"/posts/{post.Id}"))
.AssertOk()
.AssertSee(body)
.AssertDontSee(body, escape: false);
}
}Run dotnet test Blog.Tests --filter FullyQualifiedName~EscapedPostTest. AssertSee HTML-encodes its argument by default, whereas the final assertion rejects a literal executable script tag. The main walkthrough test covers the rest of the CRUD flow and authorization failures.