跳至正文

Testing ​

Introduction ​

Laravel is built with testing in mind. You can send HTTP requests through your application's middleware, routing, and handlers without starting a server, then check the responses in a few lines of code:

go
package feature_test

import (
	"testing"

	"app/tests"
)

func TestTheWelcomePageRenders(t *testing.T) {
	client := tests.New(t)

	client.Get("/").AssertOK()
}

In this test, tests.New builds your application and returns a client for it. Get sends a GET request through your middleware, routing, and error handling, as a request from a browser goes, and AssertOK checks for a 200 status code. Most of your tests should look like this one, because a test that sends a request checks your routes, middleware, and handlers together.

When a handler starts background work, the request returns once the work has finished, so the test may check what the work did.

Writing tests ​

Laravel tests are ordinary Go tests, so you run them with the tools you already use. A test is a function whose name starts with Test, in a file whose name ends in _test.go.

Your application's tests live in the tests/feature directory, in the feature_test package. New applications start with tests/feature/welcome_test.go, which checks the welcome page. Add a file beside it for each part of your application, such as posts_test.go for your posts. Each test builds your application with tests.New, which tests/tests.go defines:

go
package tests

import (
	"testing"

	"go.laravel.com/laraveltest"

	"app/bootstrap"
)

func New(t testing.TB, with ...laraveltest.Option) *laraveltest.Client {
	with = append([]laraveltest.Option{
		laraveltest.Env(map[string]string{
			"APP_ENV":              "testing",
			"APP_DEBUG":            "true",
			"BCRYPT_ROUNDS":        "4",
			"BROADCAST_CONNECTION": "discard",
			"CACHE_STORE":          "memory",
			"FEATURE_STORE":        "memory",
			"INERTIA_SSR":          "false",
			"MAIL_MAILER":          "log",
			"OTEL_SDK_DISABLED":    "true",
			"QUEUE_CONNECTION":     "sync",
			"SESSION_DRIVER":       "memory",
			"SMS_SENDER":           "log",
			"WORKFLOW_STORE":       "memory",
		}),
		laraveltest.RefreshDatabase,
	}, with...)

	return laraveltest.New(t, bootstrap.Options(), with...)
}

laraveltest.New builds the application as main.go does, from bootstrap.Options, including your services. Each option in with changes the application for one test, such as laraveltest.FakeDisk("public"). Your application's tests.New adds RefreshDatabase, so every test gets a database of its own. Keep what every test needs in tests.New, so each test only names what it changes. Tests of your jobs, listeners, and commands use tests.New too, so they belong in tests/feature as well.

Code that only computes a value, such as a function that prices an order, doesn't need the application. Test it with a plain Go test beside the code, in the same package:

go
package orders

import "testing"

func TestShippingIsFreeOverFiftyDollars(t *testing.T) {
	if got := Shipping(Order{Subtotal: 6000}); got != 0 {
		t.Errorf("shipping was %d, want 0", got)
	}
}

When an assertion fails, it reports the failure on the test, with what it expected and the response it got, and the test carries on. Each assertion returns the response, so you may chain them:

go
client.Get("/").AssertOK().AssertSee("Laravel").AssertHeader("Content-Type", "text/html; charset=utf-8")

Each call to tests.New builds a new application that has its own services, clock, sessions, and configuration, so one test can't change what another sees, and tests may run in parallel with t.Parallel().

Running tests ​

Run your tests with Go's test runner. To run only some of them, name the package and pass a pattern that matches part of their names:

shell
go test ./...

go test ./tests/feature -run Invitations

The application under test logs to the test, so a failing test shows each request it sent and each error the application reported. Pass -v to see the log of passing tests too. On your CI server, add -race to run your tests with Go's race detector, which finds handlers that share data without a lock.

Configuring your tests ​

laraveltest.New reads your .env file (with variables set in your shell taking precedence), sets APP_ENV to testing, and applies the overrides passed with laraveltest.Env in tests/tests.go. Any variable in .env that tests/tests.go doesn't override, such as DATABASE_URL or your application's own API keys, takes effect as usual.

If a variable in .env is missing or empty, such as APP_KEY in CI without a .env file, laraveltest.New fills in a fresh APP_KEY and the same fast, in-memory fallbacks that tests/tests.go sets so your tests still run.

To change a variable for every test, add or edit an entry in laraveltest.Env inside tests/tests.go. To let a .env value take effect instead of an override in tests/tests.go, such as testing against a Redis cache configured in .env, remove that entry from tests/tests.go.

You may also create a .env.testing file in your project root. When .env.testing exists, laraveltest.New reads it instead of .env, and the overrides in tests/tests.go still apply on top of it.

To override a variable for one test, pass laraveltest.Env to tests.New. Later laraveltest.Env options layer on top of earlier ones, and they configure both Laravel's settings and the settings your services and packages read. For example, this test checks a page with debug mode off, as production runs:

go
func TestErrorsHideTheirDetailsInProduction(t *testing.T) {
	client := tests.New(t, laraveltest.Env(map[string]string{
		"APP_DEBUG": "false",
	}))

	client.Get("/reports/broken").AssertStatus(500).AssertDontSee("connection refused")
}

The same option sets variables your own services read from env in services.New:

go
func TestPricesAreShownInEuros(t *testing.T) {
	client := tests.New(t, laraveltest.Env(map[string]string{
		"BILLING_CURRENCY": "eur",
	}))

	client.Get("/pricing").AssertSee("€")
}

Pass an empty string, such as "STRIPE_KEY": "", to clear a variable inherited from .env for a single test.

Making requests ​

The client has a method for each HTTP method. Each takes a path, which may include a query string, and returns a *webtest.Response for chaining assertions:

go
func TestPostsAreListed(t *testing.T) {
	client := tests.New(t)

	client.Get("/posts?page=2").AssertOK().AssertSee("Posts")
}

Post, Put, and Patch take the form to send, and Delete and Head take only the path. The client sends Sec-Fetch-Site: same-origin with each request, as a browser does for your own pages, so its requests pass CSRF protection without a token.

Named routes ​

To avoid hardcoding paths that your router already names, build URLs with client.Route, client.SignedRoute, and client.TemporarySignedRoute. Each fails the test if the route name or parameters are invalid:

go
post := client.Create(factories.Post)

client.Get(client.Route("posts.show", "post", &post)).AssertOK()

link := client.TemporarySignedRoute("invitations.accept", time.Hour, "invitation", invitation.ID)
client.Get(link).AssertOK()

Customizing request headers ​

WithHeader returns a client that sends a header with every request:

go
client.WithHeader("Accept-Language", "fr").Get("/").AssertSee("Bienvenue")

To authenticate an API request with a bearer token, call WithToken, which sets the Authorization header:

go
client.WithToken("test-token").GetJSON("/api/user").AssertOK()

The client that WithHeader or WithToken returns shares its cookies with the client it came from, so you may add a header for a single request without losing the session.

Requests come from the address 192.0.2.1. To send them from another IP address, such as when you test trusted proxies or rate limits, use WithIP:

go
client.WithIP("203.0.113.7").Post("/login", nil).AssertRedirect("/login")

Sending input ​

Post, Put, and Patch send a form, as a browser submits one, so a form that fails validation redirects back with its errors. The form is a url.Values, the standard library's type for form fields, and nil sends no input. To send JSON to an API instead, use PostJSON, PutJSON, or PatchJSON, which Testing JSON APIs covers:

go
func TestUsersCanSignUp(t *testing.T) {
	client := tests.New(t)

	client.Post("/sign-up", url.Values{
		"name":                  {"Taylor"},
		"email":                 {"taylor@laravel.com"},
		"password":              {"secret123"},
		"password_confirmation": {"secret123"},
	}).AssertRedirect("/dashboard")

	client.PostJSON("/api/users", map[string]any{"name": "Abigail", "email": "abigail@laravel.com"}).
		AssertCreated()
}

To send a raw body exactly as you wrote it, such as a signed webhook payload, use PostBody, PutBody, or PatchBody with the content type and bytes:

go
client.WithHeader("Stripe-Signature", signature).
	PostBody("/webhooks/stripe", "application/json", []byte(`{"type": "invoice.paid"}`)).
	AssertOK()

For any other HTTP method or custom request setup, build an *http.Request with httptest.NewRequest and send it with Do:

go
request := httptest.NewRequest("POST", "/webhooks/stripe", strings.NewReader(`{"type": "invoice.paid"}`))
request.Header.Set("Content-Type", "application/json")

client.Do(request).AssertOK()

Uploading files ​

To test a file upload, call Upload, which sends a multipart form in a POST request with the fields and files you give it. A webtest.File names the form field, the file, and the file's content, which you may read from a fixture in your testdata directory:

go
png, err := os.ReadFile("testdata/avatar.png")
if err != nil {
	t.Fatal(err)
}

client.Upload("/profile/avatar", url.Values{"caption": {"Me"}}, webtest.File{
	Field:   "avatar",
	Name:    "avatar.png",
	Content: png,
}).AssertRedirect("/profile")

To test a size limit or an image upload without keeping a fixture file in your repository, use webtest.FakeFile(field, name, kilobytes), which makes a file of that size, or webtest.FakeImage(field, name, width, height), which makes a valid PNG of those dimensions:

go
client.Upload("/profile/avatar", nil, webtest.FakeImage("avatar", "avatar.png", 640, 480)).
	AssertRedirect("/profile")

client.Upload("/documents", nil, webtest.FakeFile("document", "report.pdf", 6000)).
	AssertInvalid("document")

Because FakeFile fills the file with zeros, validation rules that check what a file contains, such as rule.Image and rule.Mimes, reject it.

Cookies and sessions ​

The client keeps the cookies it receives and sends them with its later requests, as a browser does. So one test can follow a visitor across several requests, and the session carries over from each request to the next:

go
func TestTheCartRemembersItsItems(t *testing.T) {
	client := tests.New(t)

	client.Post("/cart", url.Values{"product": {"42"}}).AssertRedirect("/cart")

	client.Get("/cart").AssertOK().AssertSee("1 item")
}

Every test starts with no session. To start one with data already in it, such as a coupon that an earlier page stored, call WithSession. Then use AssertSessionHas and AssertSessionMissing to check what the handler stored or flashed:

go
client.WithSession(map[string]any{"coupon": "WELCOME10"}).
	Post("/checkout", nil).
	AssertRedirect("/orders").
	AssertSessionHas("status", "Order placed!").
	AssertSessionMissing("coupon")

Session keys may use dot notation, such as settings.theme. Use AssertSessionPresent to check only that a key has a value, or AssertSessionWhere to check the value with a function of your own, whose argument type is the type to read the value as:

go
client.Post("/cart", url.Values{"product": {"7"}}).
	AssertSessionPresent("cart").
	AssertSessionWhere("cart", func(cart []int) bool { return slices.Contains(cart, 7) })

The session assertions work only on routes that run the session middleware, such as the routes in routes/web.go.

To send a cookie of your own, call WithCookie with its plain value, even when the route encrypts its cookies. On the response, AssertCookie checks a cookie's value as your application set it, before encryption, and AssertCookieExpired checks that the response removes a cookie. AssertCookiePresent and AssertCookieMissing check whether the response sets a cookie at all:

go
client.WithCookie("theme", "dark").Get("/").AssertSee("dark")

client.Post("/theme", url.Values{"theme": {"dark"}}).AssertCookie("theme", "dark")

client.Post("/tour/dismiss", nil).AssertCookieExpired("tour")

A client acts as one browser. Every client you make from it with WithHeader, WithCookie, From, or ActingAs shares its cookies, and so shares its session. To follow a second visitor, or the same user on a second device, call NewBrowser. It returns a client of the same application, with the same database, clock, and fakes, but with a cookie jar of its own. For example, this test checks that changing a password logs the user out on their other devices:

go
func TestChangingThePasswordLogsOutOtherDevices(t *testing.T) {
	client := tests.New(t)
	client.Create(factories.User, func(u *models.User) { u.Email = "taylor@laravel.com" })
	login := url.Values{"email": {"taylor@laravel.com"}, "password": {"password"}}

	laptop := client
	laptop.Post("/login", login).AssertAuthenticated()
	phone := client.NewBrowser()
	phone.Post("/login", login).AssertAuthenticated()

	laptop.Put("/settings/password", url.Values{
		"current_password":      {"password"},
		"password":              {"new-password"},
		"password_confirmation": {"new-password"},
	}).AssertValid()

	laptop.Get("/dashboard").AssertOK()
	phone.Get("/dashboard").AssertRedirect("/login")
}

Calling tests.New a second time doesn't give you a second browser. It builds a separate application that has its own encryption key, database transaction, and clock.

Acting as a user ​

Most pages of an application are for logged-in users, such as a dashboard. To send a request as a user, create one with a factory and pass it to ActingAs, which returns a client whose requests are that user's:

go
package feature_test

import (
	"testing"

	"app/database/factories"
	"app/tests"
)

func TestUsersSeeTheirDashboard(t *testing.T) {
	client := tests.New(t)
	user := client.Create(factories.User)

	client.ActingAs(&user).Get("/dashboard").AssertOK()
}

To check who is logged in after a login, registration, or logout request, use AssertAuthenticated, AssertAuthenticatedAs(&user), or AssertGuest. They read the session that the request left, so a request sent with ActingAs counts as a guest's unless your handler logs the user in. A user from your factory has the password password:

go
client.Post("/login", url.Values{"email": {user.Email}, "password": {"password"}}).
	AssertRedirect("/dashboard").
	AssertAuthenticatedAs(&user)

client.NewBrowser().Post("/login", url.Values{"email": {user.Email}, "password": {"wrong"}}).
	AssertGuest()

To learn more, check out the authentication guide's section on testing.

Following redirects ​

A form usually answers with a redirect, and the visitor sees the page the redirect leads to. The client follows each redirect as a browser does: it sends a GET request with the cookies it received, so one request checks both steps. AssertRedirect checks where the request you sent redirected, and the assertions after it check the page the visitor lands on, including its flash message:

go
client.Post("/posts", url.Values{"title": {"Hello"}}).
	AssertRedirect("/posts").
	AssertOK().
	AssertSee("Post created!")

The validation and session assertions read the session as the request you sent left it, before the client followed its redirect, so they still see the errors and data it flashed.

The client stops at a redirect to another site, such as a payment provider's checkout, and returns that redirect for you to check with AssertRedirect. To check a redirect's own status or headers, send the request with WithoutRedirects:

go
client.WithoutRedirects().Post("/posts", url.Values{"title": {"Hello"}}).
	AssertFound().
	AssertHeader("Location", "/posts")

Redirecting back ​

A form that fails validation sends the browser back to the page it came from and flashes the errors and the input it sent. Tell the test client which page the request came from with From, then check the redirect with AssertRedirectBackWithErrors:

go
func TestSignUpsNeedAValidEmail(t *testing.T) {
	client := tests.New(t)

	form := url.Values{"name": {"Taylor"}, "email": {"taylor"}, "password": {"secret123"}}

	client.From("/sign-up").Post("/sign-up", form).
		AssertRedirectBackWithErrors("email").
		AssertSessionHasInput("email", "taylor").
		AssertSessionMissingInput("password")
}

From sets the request's Referer header. AssertRedirectBack checks only the redirect, and AssertRedirectBackWithoutErrors also checks that validation passed. AssertSessionHasInput checks the old input that the next page's form shows, and password fields are never flashed.

Available assertions ​

Every assertion on a response returns the response, so you can chain several checks together. Besides the assertions below, dedicated sections cover cookies and sessions, authentication, JSON, Inertia, views, head metadata, and errors.

Status assertions ​

Use AssertStatus with a status code, or call one of the named assertions for common HTTP statuses:

go
client.Get("/posts").AssertOK()
client.PostJSON("/api/posts", map[string]any{"title": "Hello"}).AssertCreated()
client.Delete("/api/posts/1").AssertNoContent()
client.Get("/missing").AssertNotFound()
client.Get("/custom").AssertStatus(http.StatusTeapot)
AssertionAsserts
AssertStatus(status)The exact status code
AssertOK(), AssertCreated(), AssertAccepted(), AssertNoContent()A 200, 201, 202, or 204 with an empty body
AssertSuccessful(), AssertClientError(), AssertServerError()Any 2xx, 4xx, or 5xx status
AssertBadRequest(), AssertUnauthorized(), AssertPaymentRequired(), AssertForbidden(), AssertNotFound()A 400, 401, 402, 403, or 404
AssertMethodNotAllowed(), AssertNotAcceptable(), AssertRequestTimeout(), AssertConflict(), AssertGone()A 405, 406, 408, 409, or 410
AssertUnsupportedMediaType(), AssertUnprocessable(), AssertFailedDependency(), AssertTooManyRequests()A 415, 422, 424, or 429
AssertInternalServerError(), AssertServiceUnavailable()A 500 or 503

Redirect assertions ​

To check where a request redirected, pass the path or URL to AssertRedirect. To check that it redirected to a named route, use AssertRedirectToRoute with the route's name and parameters, as urls.Route takes them. AssertRedirectToSignedRoute also checks that the URL has a valid signature that hasn't expired:

go
client.Post("/posts", url.Values{"title": {"Hello"}}).AssertRedirect("/posts")

client.Post("/orders", url.Values{"plan": {"pro"}}).AssertRedirectToRoute("orders.show", "order", 1)

client.Post("/invitations", url.Values{"email": {"abigail@laravel.com"}}).
	AssertRedirectToSignedRoute("invitations.accept", "invitation", 7)
AssertionAsserts
AssertRedirect(location), AssertRedirectContains(text)That the request you sent redirected to the path or URL, or to a location that contains the text
AssertRedirectToRoute(name, params...)A redirect to the named route
AssertRedirectToSignedRoute(name, params...)A redirect to a valid signed URL of the named route
AssertRedirectBack(), AssertRedirectBackWithErrors(fields...), AssertRedirectBackWithoutErrors()A redirect back to the page the request came from
AssertMovedPermanently(), AssertFound(), AssertNotModified(), AssertTemporaryRedirect(), AssertPermanentRedirect()A 301, 302, 304, 307, or 308, which you see only without following redirects

Header and download assertions ​

To check a response's headers, or that a response downloads a file, use the header and download assertions:

go
client.Get("/api/posts").
	AssertHeader("X-Request-Id", "req_123").
	AssertHeaderContains("Cache-Control", "no-store").
	AssertHeaderPresent("ETag").
	AssertHeaderMissing("X-Powered-By")

client.Get("/invoices/1/download").AssertOK().AssertDownload("invoice-1.pdf")
AssertionAsserts
AssertHeader(key, value), AssertHeaderContains(key, text)A header's exact value, or part of it
AssertHeaderPresent(key), AssertHeaderMissing(key)That the response has the header, or doesn't
AssertDownload(name)That the response downloads a file with the name

Content assertions ​

To check the text or HTML in a response's body, use the content assertions:

go
client.Get("/posts").
	AssertOK().
	AssertSee("Taylor's Post").
	AssertDontSee("Draft Post").
	AssertSeeInOrder("First Post", "Second Post").
	AssertSeeHTML("<h1>Posts</h1>")
AssertionAsserts
AssertSee(text), AssertDontSee(text)That the body contains the text, or doesn't, as written or as a template escapes it
AssertSeeInOrder(texts...)That the body contains the texts in order
AssertSeeHTML(markup), AssertDontSeeHTML(markup)That the body contains the markup exactly as written, or doesn't

Validation assertions ​

To check which fields failed or passed validation, use the validation assertions. They read the errors from a 422 JSON response, or from the session when a form was sent back:

go
client.Post("/sign-up", url.Values{"name": {"Taylor"}, "email": {"not-an-email"}}).
	AssertInvalid("email", "password").
	AssertValid("name").
	AssertInvalidMessage("email", "valid email")

client.Post("/settings/password", url.Values{"password": {"short"}}).
	AssertInvalidIn("password", "password")
AssertionAsserts
AssertInvalid(fields...)That validation failed with an error for each field
AssertValid(fields...)That none of the fields has an error, or with no fields, that validation passed
AssertInvalidMessage(field, text)That one of the field's error messages contains the text
AssertInvalidIn(bag, fields...), AssertInvalidMessageIn(bag, field, text), AssertValidIn(bag, fields...)The same checks, for a form that puts its errors in a named bag

Inspecting responses directly ​

For a check that no assertion covers, read the response's Status, Header, and Body fields, and report with t.Errorf, as in any Go test. Cookie(name) returns a cookie that the response set, holding its decrypted value, and JSON[T]() decodes the body into a value of type T. The Request field holds the request as your application saw it, such as which route answered:

go
res := client.Get("/users/7").AssertOK()

if name := res.Request.Route().Name; name != "users.show" {
	t.Errorf("the route was %q", name)
}

t.Log(res.Body)

Go shows what a test logs only when the test fails, or when you pass -v to go test.

Testing JSON APIs ​

GetJSON sends a GET request that asks for JSON back. PostJSON, PutJSON, and PatchJSON do the same and send a value of yours as the JSON body, such as a struct or a map. DeleteJSON sends a DELETE request that asks for JSON back, with an optional JSON body.

AssertJSON checks that the body contains a value. Mirror the structure down to the fields you care about, and Laravel ignores the keys of an object that you don't mention, such as id, email, or meta, and the items of a list after the ones you give. A list's items are compared in order, starting from the first. For example, if /api/users returns:

json
{
	"data": [
		{ "id": 1, "name": "Taylor", "email": "taylor@laravel.com" },
		{ "id": 2, "name": "Abigail", "email": "abigail@laravel.com" }
	],
	"meta": { "total": 2 }
}

You only need to give the keys you want to check:

go
func TestUsersAreListed(t *testing.T) {
	client := tests.New(t)

	client.GetJSON("/api/users").AssertOK().AssertJSON(map[string]any{
		"data": []any{
			map[string]any{"name": "Taylor"},
			map[string]any{"name": "Abigail"},
		},
	})
}

When the assertion fails, the failure names where the JSON first differs, such as data.1.name.

To check one value by its dot path, call AssertJSONPath. A path's segments are object keys and list indexes, so data.0.name reads the first user's name. To count the items of a list or object, use AssertJSONCount, where the path "" counts the body itself:

go
client.GetJSON("/api/users").
	AssertJSONPath("data.0.name", "Taylor").
	AssertJSONCount("data", 2)

To check a value with your own code, pass a function to AssertJSONPathWhere, whose argument type is the type to read the value as. To check that a path has no value, use AssertJSONMissingPath:

go
client.GetJSON("/api/users").
	AssertJSONPathWhere("meta.total", func(total int) bool { return total >= 2 }).
	AssertJSONMissingPath("data.0.password")

To match the whole body, with no other keys or items, use AssertExactJSON, or AssertSimilarJSON to accept lists in any order.

Whereas AssertJSON matches from the top of the body, AssertJSONFragment checks that an object appears anywhere in it, such as one user in a list, and AssertJSONMissing checks that it appears nowhere:

go
client.GetJSON("/api/users").
	AssertJSONFragment(map[string]any{"name": "Taylor", "role": "admin"}).
	AssertJSONMissing(map[string]any{"name": "Jess"})

To check the keys and nesting of a body without pinning down its values, use AssertJSONStructure. A list names required keys, a map gives the structure of each key's value, and the key * gives the structure of every item in a list:

go
client.GetJSON("/api/users").AssertJSONStructure(map[string]any{
	"data": map[string]any{"*": []any{"id", "name", map[string]any{"team": []any{"id", "name"}}}},
	"meta": []any{"total"},
})

Use AssertExactJSONStructure if a key that the structure doesn't name should also fail the test.

To work with the body as your own type, decode it with JSON[T](), which fails the test when the body isn't valid JSON for that type. A field matches only the key with exactly its name, so give each field a json tag:

go
type usersResponse struct {
	Data []struct {
		Name string `json:"name"`
	} `json:"data"`
}

body := client.GetJSON("/api/users").AssertOK().JSON[usersResponse]()

Fluent JSON assertions ​

An API response can start sending a field nobody meant to send, such as a sensitive column added to a model. AssertJSONMatches passes the body to a function of yours as a *webtest.JSON, and fails if any key in the body is left unchecked, unless you allow the rest with Etc:

go
package feature_test

import (
	"testing"

	"go.laravel.com/webtest"

	"app/tests"
)

func TestUsersAreShownWithoutTheirPassword(t *testing.T) {
	client := tests.New(t)

	client.GetJSON("/api/users/1").AssertJSONMatches(func(j *webtest.JSON) {
		j.Equals("id", 1).
			Equals("name", "Taylor").
			Missing("password").
			Scope("team", func(team *webtest.JSON) { team.Has("id").Etc() })
	})
}

Use Scope to check the object or list at a path, with paths inside the function that start there, First to check a list's first item, Each to check every item, and Etc to allow the keys you don't check:

go
client.GetJSON("/api/users").AssertJSONMatches(func(j *webtest.JSON) {
	j.Count("data", 2).
		First("data", func(user *webtest.JSON) { user.Equals("name", "Taylor").Etc() }).
		Each("data", func(user *webtest.JSON) {
			user.Where("id", func(id int) bool { return id > 0 }).Missing("password").Etc()
		}).
		Etc()
})
MethodAsserts
Has(path), HasAny(paths...), Missing(path)That a path has a value, that one of the paths does, or that it has none
Equals(path, want)The value at a path
Where(path, check)That the value at a path passes your check, read as the function's argument type
Contains(path, item)That a list or object has the item
Count(path, n), CountBetween(path, least, most)How many items a list or object has
Scope(path, check), First(path, check), Each(path, check)The value at a path, a list's first item, or each item, with a function of its own
Etc()Nothing: it allows the keys the function doesn't check

Testing Inertia pages ​

To test an Inertia page, call AssertInertia with the page's component, then check its props by their dot paths with AssertProp and AssertPropMissing:

go
client.Get("/users/1").
	AssertOK().
	AssertInertia("Users/Show").
	AssertProp("user.name", "Taylor").
	AssertPropMissing("user.password")

For deferred props, flash data, partial reloads, and checking every prop with AssertInertiaMatches, check out the Inertia guide's section on testing pages.

Testing views ​

A response that rendered a view keeps the view's name and the data your handler passed it, so you may check them without matching the HTML. AssertViewIs checks the name, and AssertViewHas checks a value at a dot path across map keys, exported struct fields, zero-argument exported methods (such as a paginator's Items), and slice indexes, such as Users.0.Name or Posts.Items.0.Title:

go
func TestTheUserListShowsEachUser(t *testing.T) {
	client := tests.New(t)
	client.Create(factories.User, func(u *models.User) { u.Name = "Taylor" })

	client.Get("/users").
		AssertOK().
		AssertViewIs("users.index").
		AssertViewHas("Users.0.Name", "Taylor")
}

To compare the whole page with a view rendered from the data you expect, use AssertRenders, which the views guide's section on testing views describes.

Testing head metadata ​

To check a page's head metadata, such as its title and social tags, use AssertTitle, AssertMeta, and AssertMetaMissing. They read the <head> of an HTML page or the head prop of an Inertia page, so one test works for both:

go
client.Get("/posts/1").
	AssertOK().
	AssertTitle("Hello World · Laravel").
	AssertMeta("og:title", "Hello World · Laravel").
	AssertMetaMissing("robots")

For structured data, links such as a canonical URL, and the rest of the head assertions, check out the head guide's section on testing the head.

Testing errors ​

A response rendered for an error keeps the error it came from, so you can check the error itself instead of matching the page's text. For example, say your checkout handler fails with store.ErrCardDeclined when a card is declined. AssertError checks the response's error as errors.Is does, and AssertErrorWhere finds an error of a type, as errors.As does, and checks its fields:

go
client.Post("/checkout", nil).AssertPaymentRequired().AssertError(store.ErrCardDeclined)

client.Post("/checkout", nil).AssertErrorWhere(func(err *store.DeclinedError) bool {
	return err.Reason == "insufficient funds"
})

AssertReported checks that the request reported a matching error, either because the request failed with it or because your code passed it to r.Report. AssertNotReported checks that the request reported no matching error, and AssertNothingReported checks that it reported no errors at all.

When laravel.Report reports an error outside a request, such as from a job, no response holds that error. Call AssertReported on the client instead, which checks every error the application reported during the test. To learn more, check out the error handling guide's section on testing errors.

Testing the database ​

A test that signs a user up or places an order needs a database with your tables in it, and with no rows left over from the tests before it. Laravel gives each test a database that your migrations built, and rolls back what the test wrote when the test ends.

Refreshing the database ​

Your application's tests.New passes laraveltest.RefreshDatabase to laraveltest.New, so every test it builds has a database:

go
package feature_test

import (
	"net/url"
	"testing"

	"go.laravel.com/db"

	"app/tests"
)

func TestPublishingAPostSavesIt(t *testing.T) {
	client := tests.New(t)

	client.Post("/posts", url.Values{"title": {"Hello"}}).AssertRedirect("/posts")

	client.AssertDatabaseHas("posts", db.Values{"title": "Hello"})
}

Tests don't run against the database that DATABASE_URL names, because they would change your development data. Instead, each test package borrows a numbered copy of a test database beside it, which no other running package uses, so go test ./... can run your packages at once. For example, when DATABASE_URL is postgres://postgres@127.0.0.1/laravel, tests use laravel_test_1, laravel_test_2, and so on. RefreshDatabase uses DATABASE_URL from your .env or .env.testing file, your shell's environment, or laraveltest.Env. It creates the copies on PostgreSQL and MySQL, so the database user needs permission to create databases. On SQLite, each client gets a new database in memory instead.

The copies stay between test runs, so your tests don't wait for the migrations every time. When your application's code or the package's tests change, including a migration, Laravel rebuilds the package's copy from all of your migrations. If you've squashed your migrations into a schema file, Laravel loads that file first and then runs only the migrations you've added since, which builds a test database much faster when you have hundreds of migrations. Changing the schema file rebuilds the copy too.

If your application has no database, remove laraveltest.RefreshDatabase from tests/tests.go, and your tests won't need a database server.

Each client runs in a transaction that's never committed, so its changes disappear when the test ends. The client's requests, its factories, and the code you call with client.Context() all use that transaction, and your application's own transactions run as savepoints inside it. Keep these differences in mind:

  • Auto-increment IDs keep counting from one test to the next, because a rollback doesn't reset them. Assert the IDs that your application returns, not fixed ones such as 1.
  • Create tables in migrations, not in tests. On MySQL, a statement such as CREATE TABLE commits the transaction.
  • Rows that a test writes aren't visible to other connections, such as a queue worker you started yourself.

To give a test the rows it needs, create them with the client's Create and a model factory, as in Acting as a user. Create inserts the model through the client's transaction and fails the test when the insert fails.

Seeding the database ​

If a test only needs one or two records, prefer model factories over a seeder, so each test shows the data it relies on:

go
user := client.Create(factories.User)

posts := client.CreateMany(3, factories.Post.For("user", user))

When a test needs a larger set of rows, call the client's Seed with the name of one of your seeders. It runs in the client's transaction, so its rows disappear when the test ends. With no names, it runs every seeder, as db:seed does:

go
func TestTheArchiveListsEveryPost(t *testing.T) {
	client := tests.New(t)

	client.Seed("posts").Get("/archive").AssertOK().AssertSee("Archive")
}

When most of your tests need the same rows, such as your roles, seed each copy of the test database once instead. Add laraveltest.SeedOnce beside RefreshDatabase in tests/tests.go:

go
func New(t testing.TB, with ...laraveltest.Option) *laraveltest.Client {
	with = append([]laraveltest.Option{
		laraveltest.RefreshDatabase,
		laraveltest.SeedOnce("roles"),
	}, with...)

	return laraveltest.New(t, bootstrap.Options(), with...)
}

The seeders run right after the migrations rebuild a copy, and their rows are committed. Each test rolls back only its own changes, so every test starts with the seeded rows, including tests that count or list rows. Like the migrations, the seeders run again when your code or tests change, and they run without the test's fakes.

The tests of a package share one copy, so every test of a package needs the same SeedOnce, which is why tests.New is the place for it. A test that passes other seeders fails and says which seeders the copy has.

Both Seed and SeedOnce need RefreshDatabase, so a test can't write seed data to your development database.

Database assertions ​

To check what your application wrote, use AssertDatabaseHas and the other database assertions on the client. Each one reads the table through the client's transaction:

go
func TestCancellingAnImportFailsIt(t *testing.T) {
	client := tests.New(t)

	client.Post("/imports/7/cancel", nil).AssertRedirect("/imports")

	client.AssertDatabaseHas("imports", db.Values{"id": 7, "status": "failed"})
	client.AssertDatabaseMissing("imports", db.Values{"id": 7, "failed_at": nil})
	client.AssertDatabaseEmpty("import_chunks")
}
AssertionAsserts
AssertDatabaseHas(table, values)That a row has all the given column values
AssertDatabaseMissing(table, values)That no row has all the given column values
AssertDatabaseCount(table, count)That the table has exactly count rows
AssertDatabaseEmpty(table)That the table has no rows
AssertModelExists(&model)That the model's row exists, found by its ID
AssertModelMissing(&model)That the model's row doesn't exist

A nil value matches NULL. When AssertDatabaseHas fails, it shows the table's first rows, so you can see what your application wrote instead.

The assertions read your default database. If your application writes to a named connection, such as audit rows in a reporting database, call OnConnection with the connection's name first:

go
client.OnConnection("reporting").AssertDatabaseCount("audits", 1)

You may also load a model with client.Context() and check its fields yourself, which is often clearer for dates and computed values:

go
imported, err := model.Find[models.Import](client.Context(), importID)
if err != nil {
	t.Fatal(err)
}

if imported.FailedAt == nil {
	t.Error("the import has no failed_at time")
}

Fakes ​

Instead of calling external APIs, sending real emails, or running external processes in your tests, Laravel provides fakes that record what your application sent so you can check it. Build the client first, then pass it to each fake's New, which installs the fake in that client's application and returns it. Once the request has run, check what it sent with the fake's own assertions:

go
func TestPlacingAnOrder(t *testing.T) {
	client := tests.New(t)
	dispatched := eventtest.New(client)
	emails := mailtest.New(client)

	client.Post("/orders", url.Values{"total": {"2500"}}).AssertRedirect("/orders")

	emails.AssertSent[mails.OrderConfirmed]()
	dispatched.AssertDispatched[events.OrderPlaced]()
}

Each subsystem's guide covers its fake and assertions:

A few fakes change what a request reads rather than what it sends. The laraveltest.FakeDisk("public") option replaces storage disks with temporary directories, and feature.Fake(client.Context(), features.NewAPI, true) pins a feature flag to a value.

说明

An application holds one fake of each kind, so a second call to the same package's New for one client fails the test. Keep the fake that the first call returned.

Replacing dependencies ​

To test code that talks to an external system, such as a payment provider, replace the service your application uses with one that doesn't leave your process. Your handlers and jobs get their services from services.From(ctx), which returns the services that services.New built for the application. Each test builds its own application, so a test may replace a service and has nothing to swap back afterwards.

If the service sends its requests with Laravel's HTTP client, fake them with httpclienttest, as Fakes shows. For a client that makes its own requests, such as a provider's SDK, point it at a server your test starts. For example, say your billing.Client calls a provider at the address in its BaseURL field. This test starts a fake provider with the standard library's httptest package, and sets the Billing field of the services that services.From(client.Context()) returns:

go
package feature_test

import (
	"io"
	"net/http"
	"net/http/httptest"
	"testing"

	"app/billing"
	"app/services"
	"app/tests"
)

func TestInvoicesAreListed(t *testing.T) {
	provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		io.WriteString(w, `[{"id": 1, "total": 4200}]`)
	}))
	t.Cleanup(provider.Close)

	billingClient := billing.NewClient("sk_test_key", "usd")
	billingClient.BaseURL = provider.URL

	client := tests.New(t)
	services.From(client.Context()).Billing = billingClient

	client.Get("/invoices").AssertOK().AssertSee("4200")
}

The application reads its services on every request, so the next request uses the replacement, and the other services stay as services.New built them.

When a service is an interface, such as a Geocoder that finds the coordinates of an address, your fake can be a small type of its own that implements the interface. This fake returns fixed coordinates and records each address it's asked about, so the test never calls the real geocoding service:

go
package feature_test

import (
	"context"
	"slices"
	"testing"

	"app/geo"
	"app/services"
	"app/tests"
)

type fakeGeocoder struct {
	addresses []string
}

func (g *fakeGeocoder) Locate(ctx context.Context, address string) (geo.Coordinates, error) {
	g.addresses = append(g.addresses, address)

	return geo.Coordinates{Latitude: 41.8781, Longitude: -87.6298}, nil
}

func TestStoresAreFoundNearTheAddress(t *testing.T) {
	client := tests.New(t)
	geocoder := &fakeGeocoder{}
	services.From(client.Context()).Geocoder = geocoder

	client.Get("/stores?address=Chicago").AssertOK()

	if !slices.Equal(geocoder.addresses, []string{"Chicago"}) {
		t.Errorf("geocoded %v, want [Chicago]", geocoder.addresses)
	}
}

警告

Replace a service before the first request that uses it, and don't change it while a request is running.

Time travel ​

To test what happens later, such as an invitation expiring, move your application's time forward instead of waiting. For example, say your invitation links work for a day:

go
package feature_test

import (
	"testing"
	"time"

	"app/tests"
)

func TestInvitationsExpireAfterADay(t *testing.T) {
	client := tests.New(t)

	type invitationResponse struct {
		Link string `json:"link"`
	}
	invitation := client.PostJSON("/invitations", nil).AssertCreated().JSON[invitationResponse]()

	client.Travel(25 * time.Hour)

	client.Get(invitation.Link).AssertForbidden()
}

Travel moves the time forward by a time.Duration. After it travels, the application's time stands still until you call TravelBack. Each method returns the client, so you may chain a request after it. You may also call these methods:

  • TravelTo(t) travels to a time.Time. For a month or a year, add it to the current time, as in client.TravelTo(client.Now().AddDate(0, 1, 0)).
  • Now() returns the application's current time, for building times that your application compares with its own, such as a post scheduled two hours from now: client.Now().Add(2 * time.Hour).
  • Freeze() stops time where it is.
  • FreezeSecond() stops time at the start of the current second, so a time your test compares with one the database stored to the second matches exactly.
  • TravelBack() returns to the present.

Laravel reads the moved time wherever it checks a time, such as for sessions, cache values, signed URLs, rate limits, delayed jobs, and model timestamps. Each test's application has its own clock, so tests running in parallel don't move each other's time. In your own code, read the time with date.Now(ctx) rather than time.Now(), so tests can move it.

Calling your code directly ​

Some code is easier to test by calling it directly than through a request, such as a listener, a model's hook, or a function that ranks posts. Call it as you would any Go function, and where it takes a context, pass client.Context(). That context carries the client's application, so your code reaches the same configuration, services, and fakes as the client's requests do, and its queries run in the client's transaction.

For example, say your application has a digest package with a function that returns a user's most-voted posts:

go
package digest

import (
	"context"

	"go.laravel.com/model"

	"app/models"
)

func PopularPosts(ctx context.Context, user models.User) ([]models.Post, error) {
	return model.Query[models.Post]().WhereEq("user_id", user.ID).OrderByDesc("votes").Limit(5).Get(ctx)
}

This test creates two posts, then calls the function with the client's context:

go
package feature_test

import (
	"testing"

	"app/database/factories"
	"app/digest"
	"app/models"
	"app/tests"
)

func TestPopularPostsStartWithTheMostVoted(t *testing.T) {
	client := tests.New(t)
	user := client.Create(factories.User)
	client.Create(factories.Post.For("user", user), func(p *models.Post) { p.Votes = 10 })
	popular := client.Create(factories.Post.For("user", user), func(p *models.Post) { p.Votes = 150 })

	posts, err := digest.PopularPosts(client.Context(), user)
	if err != nil {
		t.Fatal(err)
	}

	if len(posts) != 2 || posts[0].ID != popular.ID {
		t.Errorf("got %v, want the post with 150 votes first", posts)
	}
}

For code that reads the logged-in user with auth.User, take the context from a client that acts as the user: client.ActingAs(&user).Context(). To run one attempt of a queued job as a worker would, through its middleware, use client.Attempt, which the queues guide's section on testing a job covers.

说明

Pass client.Context(), not t.Context() or context.Background(). Those don't carry an application, so Laravel's functions panic and tell you which context to pass.

Testing console commands ​

To run a console command in a test, call the client's Command with the command line as you'd type it after laravel. The command runs in the client's application and transaction, and Laravel captures its output and exit status for you to check:

go
func TestStaleDraftsArePruned(t *testing.T) {
	client := tests.New(t)

	client.Command("posts:prune --days=30").
		AssertSuccessful().
		AssertErrorOutputContains("Deleted 2 drafts.")
}

Results from Line and Table go to standard output, so check them with AssertOutputContains. Messages from Info, Success, Warn, and Error, and the error that Run returns, go to standard error, so check them with AssertErrorOutputContains. You may also check that output is absent with AssertOutputMissing, AssertErrorOutputMissing, and AssertNoOutput.

To answer a command's prompts, pass a laraveltest.Answer for each one, in the order the command asks:

go
client.Command("user:create",
	laraveltest.Answer("What is the user's name?", "Taylor"),
	laraveltest.Answer("Create the user?", "yes"),
).AssertSuccessful()

To learn more, check out the console guide's section on testing commands.