Skip to content

Commit 12a7fb3

Browse files
committed
working on testing docs
1 parent d7afab1 commit 12a7fb3

9 files changed

Lines changed: 763 additions & 665 deletions

File tree

application-testing.md

Lines changed: 341 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,341 @@
1+
# Application Testing
2+
3+
- [Introduction](#introduction)
4+
- [Interacting With Your Application](#interacting-with-your-application)
5+
- [Interacting With Links](#interacting-with-links)
6+
- [Interacting With Forms](#interacting-with-forms)
7+
- [Testing JSON APIs](#testing-json-apis)
8+
- [Verifying Exact Match](#verifying-exact-match)
9+
- [Verifying Structural Match](#verifying-structural-match)
10+
- [Sessions / Authentication](#sessions-and-authentication)
11+
- [Disabling Middleware](#disabling-middleware)
12+
- [Custom HTTP Requests](#custom-http-requests)
13+
- [PHPUnit Assertions](#phpunit-assertions)
14+
15+
<a name="introduction"></a>
16+
## Introduction
17+
18+
Laravel provides a very fluent API for making HTTP requests to your application, examining the output, and even filling out forms. For example, take a look at the test defined below:
19+
20+
<?php
21+
22+
use Illuminate\Foundation\Testing\WithoutMiddleware;
23+
use Illuminate\Foundation\Testing\DatabaseTransactions;
24+
25+
class ExampleTest extends TestCase
26+
{
27+
/**
28+
* A basic functional test example.
29+
*
30+
* @return void
31+
*/
32+
public function testBasicExample()
33+
{
34+
$this->visit('/')
35+
->see('Laravel 5')
36+
->dontSee('Rails');
37+
}
38+
}
39+
40+
The `visit` method makes a `GET` request into the application. The `see` method asserts that we should see the given text in the response returned by the application. The `dontSee` method asserts that the given text is not returned in the application response. This is the most basic application test available in Laravel.
41+
42+
<a name="interacting-with-your-application"></a>
43+
## Interacting With Your Application
44+
45+
Of course, you can do much more than simply assert that text appears in a given response. Let's take a look at some examples of clicking links and filling out forms:
46+
47+
<a name="interacting-with-links"></a>
48+
### Interacting With Links
49+
50+
In this test, we will make a request to the application, "click" a link in the returned response, and then assert that we landed on a given URI. For example, let's assume there is a link in our response that has a text value of "About Us":
51+
52+
<a href="/about-us">About Us</a>
53+
54+
Now, let's write a test that clicks the link and asserts the user lands on the correct page:
55+
56+
public function testBasicExample()
57+
{
58+
$this->visit('/')
59+
->click('About Us')
60+
->seePageIs('/about-us');
61+
}
62+
63+
<a name="interacting-with-forms"></a>
64+
### Interacting With Forms
65+
66+
Laravel also provides several methods for testing forms. The `type`, `select`, `check`, `attach`, and `press` methods allow you to interact with all of your form's inputs. For example, let's imagine this form exists on the application's registration page:
67+
68+
<form action="/register" method="POST">
69+
{{ csrf_field() }}
70+
71+
<div>
72+
Name: <input type="text" name="name">
73+
</div>
74+
75+
<div>
76+
<input type="checkbox" value="yes" name="terms"> Accept Terms
77+
</div>
78+
79+
<div>
80+
<input type="submit" value="Register">
81+
</div>
82+
</form>
83+
84+
We can write a test to complete this form and inspect the result:
85+
86+
public function testNewUserRegistration()
87+
{
88+
$this->visit('/register')
89+
->type('Taylor', 'name')
90+
->check('terms')
91+
->press('Register')
92+
->seePageIs('/dashboard');
93+
}
94+
95+
Of course, if your form contains other inputs such as radio buttons or drop-down boxes, you may easily fill out those types of fields as well. Here is a list of each form manipulation method:
96+
97+
Method | Description
98+
------------- | -------------
99+
`$this->type($text, $elementName)` | "Type" text into a given field.
100+
`$this->select($value, $elementName)` | "Select" a radio button or drop-down field.
101+
`$this->check($elementName)` | "Check" a checkbox field.
102+
`$this->uncheck($elementName)` | "Uncheck" a checkbox field.
103+
`$this->attach($pathToFile, $elementName)` | "Attach" a file to the form.
104+
`$this->press($buttonTextOrElementName)` | "Press" a button with the given text or name.
105+
106+
<a name="file-inputs"></a>
107+
#### File Inputs
108+
109+
If your form contains `file` inputs, you may attach files to the form using the `attach` method:
110+
111+
public function testPhotoCanBeUploaded()
112+
{
113+
$this->visit('/upload')
114+
->attach($pathToFile, 'photo')
115+
->press('Upload')
116+
->see('Upload Successful!');
117+
}
118+
119+
<a name="testing-json-apis"></a>
120+
### Testing JSON APIs
121+
122+
Laravel also provides several helpers for testing JSON APIs and their responses. For example, the `json`, `get`, `post`, `put`, `patch`, and `delete` methods may be used to issue requests with various HTTP verbs. You may also easily pass data and headers to these methods. To get started, let's write a test to make a `POST` request to `/user` and assert that the expected data was returned:
123+
124+
<?php
125+
126+
class ExampleTest extends TestCase
127+
{
128+
/**
129+
* A basic functional test example.
130+
*
131+
* @return void
132+
*/
133+
public function testBasicExample()
134+
{
135+
$this->json('POST', '/user', ['name' => 'Sally'])
136+
->seeJson([
137+
'created' => true,
138+
]);
139+
}
140+
}
141+
142+
> {tip} The `seeJson` method converts the given array into JSON, and then verifies that the JSON fragment occurs **anywhere** within the entire JSON response returned by the application. So, if there are other properties in the JSON response, this test will still pass as long as the given fragment is present.
143+
144+
<a name="verifying-exact-match"></a>
145+
### Verifying Exact Match
146+
147+
If you would like to verify that the given array is an **exact** match for the JSON returned by the application, you should use the `seeJsonEquals` method:
148+
149+
<?php
150+
151+
class ExampleTest extends TestCase
152+
{
153+
/**
154+
* A basic functional test example.
155+
*
156+
* @return void
157+
*/
158+
public function testBasicExample()
159+
{
160+
$this->json('POST', '/user', ['name' => 'Sally'])
161+
->seeJsonEquals([
162+
'created' => true,
163+
]);
164+
}
165+
}
166+
167+
<a name="verifying-structural-match"></a>
168+
### Verifying Structural Match
169+
170+
It is also possible to verify that a JSON response adheres to a specific structure. In this scenario, you should use the `seeJsonStructure` method and pass it your expected JSON structure:
171+
172+
<?php
173+
174+
class ExampleTest extends TestCase
175+
{
176+
/**
177+
* A basic functional test example.
178+
*
179+
* @return void
180+
*/
181+
public function testBasicExample()
182+
{
183+
$this->get('/user/1')
184+
->seeJsonStructure([
185+
'name',
186+
'pet' => [
187+
'name', 'age'
188+
]
189+
]);
190+
}
191+
}
192+
193+
The above example illustrates an expectation of receiving a `name` attribute and a nested `pet` object with its own `name` and `age` attributes. `seeJsonStructure` will not fail if additional keys are present in the response. For example, the test would still pass if the `pet` had a `weight` attribute.
194+
195+
You may use the `*` to assert that the returned JSON structure has a list where each list item contains at least the attributes found in the set of values:
196+
197+
<?php
198+
199+
class ExampleTest extends TestCase
200+
{
201+
/**
202+
* A basic functional test example.
203+
*
204+
* @return void
205+
*/
206+
public function testBasicExample()
207+
{
208+
// Assert that each user in the list has at least an id, name and email attribute.
209+
$this->get('/users')
210+
->seeJsonStructure([
211+
'*' => [
212+
'id', 'name', 'email'
213+
]
214+
]);
215+
}
216+
}
217+
218+
You may also nest the `*` notation. In this case, we will assert that each user in the JSON response contains a given set of attributes and that each pet on each user also contains a given set of attributes:
219+
220+
$this->get('/users')
221+
->seeJsonStructure([
222+
'*' => [
223+
'id', 'name', 'email', 'pets' => [
224+
'*' => [
225+
'name', 'age'
226+
]
227+
]
228+
]
229+
]);
230+
231+
<a name="sessions-and-authentication"></a>
232+
### Sessions / Authentication
233+
234+
Laravel provides several helpers for working with the session during testing. First, you may set the session data to a given array using the `withSession` method. This is useful for loading the session with data before issuing a request to your application:
235+
236+
<?php
237+
238+
class ExampleTest extends TestCase
239+
{
240+
public function testApplication()
241+
{
242+
$this->withSession(['foo' => 'bar'])
243+
->visit('/');
244+
}
245+
}
246+
247+
Of course, one common use of the session is for maintaining state for the authenticated user. The `actingAs` helper method provides a simple way to authenticate a given user as the current user. For example, we may use a [model factory](#model-factories) to generate and authenticate a user:
248+
249+
<?php
250+
251+
class ExampleTest extends TestCase
252+
{
253+
public function testApplication()
254+
{
255+
$user = factory(App\User::class)->create();
256+
257+
$this->actingAs($user)
258+
->withSession(['foo' => 'bar'])
259+
->visit('/')
260+
->see('Hello, '.$user->name);
261+
}
262+
}
263+
264+
You may also specify which guard should be used to authenticate the given user by passing the guard name as the second argument to the `actingAs` method:
265+
266+
$this->actingAs($user, 'api')
267+
268+
<a name="disabling-middleware"></a>
269+
### Disabling Middleware
270+
271+
When testing your application, you may find it convenient to disable [middleware](/docs/{{version}}/middleware) for some of your tests. This will allow you to test your routes and controller in isolation from any middleware concerns. Laravel includes a simple `WithoutMiddleware` trait that you can use to automatically disable all middleware for the test class:
272+
273+
<?php
274+
275+
use Illuminate\Foundation\Testing\WithoutMiddleware;
276+
use Illuminate\Foundation\Testing\DatabaseMigrations;
277+
use Illuminate\Foundation\Testing\DatabaseTransactions;
278+
279+
class ExampleTest extends TestCase
280+
{
281+
use WithoutMiddleware;
282+
283+
//
284+
}
285+
286+
If you would like to only disable middleware for a few test methods, you may call the `withoutMiddleware` method from within the test methods:
287+
288+
<?php
289+
290+
class ExampleTest extends TestCase
291+
{
292+
/**
293+
* A basic functional test example.
294+
*
295+
* @return void
296+
*/
297+
public function testBasicExample()
298+
{
299+
$this->withoutMiddleware();
300+
301+
$this->visit('/')
302+
->see('Laravel 5');
303+
}
304+
}
305+
306+
<a name="custom-http-requests"></a>
307+
### Custom HTTP Requests
308+
309+
If you would like to make a custom HTTP request into your application and get the full `Illuminate\Http\Response` object, you may use the `call` method:
310+
311+
public function testApplication()
312+
{
313+
$response = $this->call('GET', '/');
314+
315+
$this->assertEquals(200, $response->status());
316+
}
317+
318+
If you are making `POST`, `PUT`, or `PATCH` requests you may pass an array of input data with the request. Of course, this data will be available in your routes and controller via the [Request instance](/docs/{{version}}/requests):
319+
320+
$response = $this->call('POST', '/user', ['name' => 'Taylor']);
321+
322+
<a name="phpunit-assertions"></a>
323+
### PHPUnit Assertions
324+
325+
Laravel provides a variety of custom assertion methods for [PHPUnit](https://phpunit.de/) tests:
326+
327+
Method | Description
328+
------------- | -------------
329+
`->assertResponseOk();` | Assert that the client response has an OK status code.
330+
`->assertResponseStatus($code);` | Assert that the client response has a given code.
331+
`->assertViewHas($key, $value = null);` | Assert that the response view has a given piece of bound data.
332+
`->assertViewHasAll(array $bindings);` | Assert that the view has a given list of bound data.
333+
`->assertViewMissing($key);` | Assert that the response view is missing a piece of bound data.
334+
`->assertRedirectedTo($uri, $with = []);` | Assert whether the client was redirected to a given URI.
335+
`->assertRedirectedToRoute($name, $parameters = [], $with = []);` | Assert whether the client was redirected to a given route.
336+
`->assertRedirectedToAction($name, $parameters = [], $with = []);` | Assert whether the client was redirected to a given action.
337+
`->assertSessionHas($key, $value = null);` | Assert that the session has a given value.
338+
`->assertSessionHasAll(array $bindings);` | Assert that the session has a given list of values.
339+
`->assertSessionHasErrors($bindings = [], $format = null);` | Assert that the session has errors bound.
340+
`->assertHasOldInput();` | Assert that the session has old input.
341+
`->assertSessionMissing($key);` | Assert that the session is missing a given key.

0 commit comments

Comments
 (0)