Skip to content

Commit 528cd78

Browse files
javiereguiluzGuikingone
authored andcommitted
Documented PHPUnit data providers
1 parent 4e055b9 commit 528cd78

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

best_practices/tests.rst

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,8 @@ functional tests, you can quickly spot any big errors before you deploy them:
2727
Define a functional test that at least checks if your application pages
2828
are successfully loading.
2929

30-
A functional test can be as easy as this::
30+
A functional test like this is simple to implement thanks to
31+
:ref:`PHPUnit data providers <testing-data-providers>`::
3132

3233
// tests/ApplicationAvailabilityFunctionalTest.php
3334
namespace App\Tests;

testing.rst

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -332,6 +332,41 @@ document::
332332
// ...or simply check that the response is a redirect to any URL
333333
$this->assertTrue($client->getResponse()->isRedirect());
334334

335+
.. _testing-data-providers:
336+
337+
Testing against Different Sets of Data
338+
--------------------------------------
339+
340+
It's common to have to execute the same test against different sets of data to
341+
check the multiple conditions code must handle. This is solved with PHPUnit's
342+
`data providers`_, which work both for unit and functional tests.
343+
344+
First, add one or more arguments to your test method and use them inside the
345+
test code. Then, define another method which returns a nested array with the
346+
arguments to use on each test run. Lastly, add the ``@dataProvider`` annotation
347+
to associate both methods::
348+
349+
/**
350+
* @dataProvider provideUrls
351+
*/
352+
public function testPageIsSuccessful($url)
353+
{
354+
$client = self::createClient();
355+
$client->request('GET', $url);
356+
357+
$this->assertTrue($client->getResponse()->isSuccessful());
358+
}
359+
360+
public function provideUrls()
361+
{
362+
return array(
363+
array('/'),
364+
array('/blog'),
365+
array('/contact'),
366+
// ...
367+
);
368+
}
369+
335370
.. index::
336371
single: Tests; Client
337372

@@ -993,3 +1028,4 @@ Learn more
9931028
.. _`documentation`: https://phpunit.de/manual/current/en/
9941029
.. _`PHPUnit Bridge component`: https://symfony.com/components/PHPUnit%20Bridge
9951030
.. _`$_SERVER`: https://php.net/manual/en/reserved.variables.server.php
1031+
.. _`data providers`: https://phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.data-providers

0 commit comments

Comments
 (0)