### PHPUnit setUp() and tearDown() Example
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/fixtures.md
Demonstrates the use of setUp() to create a test fixture and tearDown() to clean it up. This method is invoked before and after each test method, respectively.
```php
assertSame(
'the-result',
$this->example->doSomething()
);
}
protected function setUp(): void
{
$this->example = new Example(
$this->createStub(Collaborator::class)
);
}
protected function tearDown(): void
{
$this->example = null;
}
}
```
--------------------------------
### PHPUnit Derived TestCase with setUp()
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/fixtures.md
Illustrates a concrete test case class extending an abstract base class and implementing its own setUp() method. Highlights the importance of calling parent::setUp() to ensure inherited setup logic is executed.
```php
assertStringStartsWith('prefix', 'foo');
}
}
```
--------------------------------
### phpunit.xml Configuration
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/error-handling.md
The PHPUnit configuration file for the example project, specifying the test suite directory and bootstrap file.
```xml
tests
```
--------------------------------
### Global PHPUnit Installation
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/installation.md
Installs PHPUnit globally using a PHAR archive. This method makes the `phpunit` command available system-wide. Ensure the PHAR file is executable and moved to a directory in your system's PATH.
```bash
wget -O phpunit.phar https://phar.phpunit.de/phpunit-10.phar
chmod +x phpunit.phar
sudo mv phpunit.phar /usr/local/bin/phpunit
phpunit --version
PHPUnit 10.0.0 by Sebastian Bergmann and contributors.
```
--------------------------------
### Registering Extension from PHAR
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/extending-phpunit.md
Configure the directory for PHAR extensions using `extensionsDirectory`. This example shows how to register a bootstrap extension with a parameter.
```xml
```
--------------------------------
### Download and Place PHPUnit PHAR in Tools Directory
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/installation.md
Download the PHPUnit PHAR to a project's `tools` directory, make it executable, and move it there. This is common for per-project installations.
```bash
wget -O phpunit.phar https://phar.phpunit.de/phpunit-10.phar
chmod +x phpunit.phar
mv phpunit.phar tools
```
--------------------------------
### Tap Homebrew PHP Formulae on macOS
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/installation.md
Adds the necessary Homebrew repositories for installing PHP and its extensions on macOS.
```bash
brew tap shivammathur/php
brew tap shivammathur/extensions
```
--------------------------------
### Test Method with Arrange, Act, Assert
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/writing-tests-for-phpunit.md
This snippet demonstrates the typical structure of a PHPUnit test method, separating setup, action, and verification steps.
```php
public function testCanBeCreatedFromValidEmail(): void
{
// Arrange
$string = 'user@example.org';
// Act
$email = Email::fromString($string);
// Assert
$this->assertSame($string, $email->asString());
}
```
--------------------------------
### Verify PHPUnit Version
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/installation.md
Check the installed PHPUnit version by running the downloaded PHAR file with the `--version` flag.
```bash
php phpunit.phar --version
```
--------------------------------
### Build HTML Documentation with make html
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/README.md
Run this command in your terminal to build the complete HTML documentation for PHPUnit. Ensure you have Python, Sphinx, and the Read the Docs Sphinx Theme installed.
```sh
make html
```
--------------------------------
### Install PHPUnit with Copy Option
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/installation.md
Use the `--copy` option with Phive to keep the PHPUnit PHAR file under version control within your project's tools directory.
```none
phive install --copy phpunit
```
--------------------------------
### TestDox Plain Text Output Example
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/testdox.md
Demonstrates the plain text output format for TestDox. Successful tests are marked with '[x]' and defective tests with '[ ]'.
```none
Greeter
[x] Greets with name
[x] Greets with good morning before noon
[x] Greets with good afternoon after noon
[x] Greets with good evening after 6 pm
```
--------------------------------
### Email Class Example
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/writing-tests-for-phpunit.md
This is the class under test. It represents an email address and includes validation.
```php
ensureIsValidEmail($email);
$this->email = $email;
}
public function asString(): string
{
return $this->email;
}
private function ensureIsValidEmail(string $email): void
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new InvalidArgumentException(
sprintf(
"%s" is not a valid email address",
$email,
),
);
}
}
}
```
--------------------------------
### Invoke Project-Local PHPUnit
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/installation.md
Execute PHPUnit from your project's vendor directory. This command shows how to check the installed PHPUnit version.
```none
./vendor/bin/phpunit --version
PHPUnit 10.0.0 by Sebastian Bergmann and contributors.
```
--------------------------------
### Verify PHP Version
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/installation.md
Checks the installed PHP command-line interpreter version and confirms it is on the system's PATH.
```bash
php --version
```
--------------------------------
### assertEquals() with objects
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/assertions.md
Compares two objects for equality based on their property values. This example demonstrates a failure where properties do not match.
```PHP
foo = 'foo';
$expected->bar = 'bar';
$actual = new stdClass;
$actual->foo = 'bar';
$actual->baz = 'bar';
$this->assertEquals($expected, $actual);
}
}
```
--------------------------------
### PHPUnit assertStringMatchesFormatFile() Example
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/assertions.md
Illustrates a failure scenario for `assertStringMatchesFormatFile()`. This assertion verifies if a string matches the format defined in a specified file.
```php
assertStringMatchesFormatFile(
__DIR__ . '/expected-format.txt',
'foo',
);
}
}
```
--------------------------------
### Registering Extension from Composer Package
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/extending-phpunit.md
Register a bootstrap extension with a parameter when PHPUnit is installed via Composer. No `extensionsDirectory` is needed as Composer handles autoloading.
```xml
```
--------------------------------
### Implement TestPreparationStartedSubscriber
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/extending-phpunit.md
Use this subscriber to execute logic just before a test begins, such as before the setUp() method runs. It accesses the test ID and current time from the event object.
```php
printer->testPreparationStarted(
$event->test()->id(),
$event->telemetryInfo()->time()
);
}
}
```
--------------------------------
### Using Attributes for Setup and Teardown Phases in PHPUnit
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/fixtures.md
PHPUnit provides attributes like Before and After to mark methods for specific phases, allowing multiple methods to be configured for the same phase, especially useful in class hierarchies.
```php
'foo'
'bar' => 'bar'
'baz' => 'bar'
)
/path/to/tests/EqualsWithObjectsTest.php:16
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
```
```php
assertEquals(['a', 'b', 'c'], ['a', 'c', 'd']);
}
}
```
```none
./tools/phpunit tests/EqualsWithArraysTest.php
PHPUnit 13.2.0 by Sebastian Bergmann and contributors.
Runtime: PHP 8.5.7
F 1 / 1 (100%)
Time: 00:00, Memory: 28.00 MB
There was 1 failure:
1) EqualsWithArraysTest::testFailure
Failed asserting that two arrays are equal.
--- Expected
+++ Actual
@@ @@
Array (
0 => 'a'
1 => 'b'
2 => 'c'
)
/path/to/tests/EqualsWithArraysTest.php:8
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
```
--------------------------------
### Skip Test if PostgreSQL Extension Not Available
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/writing-tests-for-phpunit.md
Use `markTestSkipped()` in the `setUp()` method to skip a test if a specific PHP extension is not loaded. This is useful for tests that depend on external resources or configurations.
```php
markTestSkipped(
'The PostgreSQL extension is not available',
);
}
}
public function testConnection(): void
{
// ...
}
}
```
--------------------------------
### Share Database Connection with setUpBeforeClass and tearDownAfterClass
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/fixtures.md
Use setUpBeforeClass() to establish a database connection before the first test and tearDownAfterClass() to close it after the last test in a class. This can improve test performance by avoiding repeated connection overhead.
```php
assertSame($expected, $a + $b);
}
}
```
--------------------------------
### Implement PHPUnit Extension Entry Point
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/extending-phpunit.md
This class serves as the entry point for a PHPUnit extension, implementing the `bootstrap` method to register event subscribers and configure output replacement.
```php
replaceOutput();
$printer = new Printer;
$facade->registerSubscribers(
new Subscriber\TestPreparationStartedSubscriber($printer),
new Subscriber\TestPassedSubscriber($printer),
new Subscriber\TestFailedSubscriber($printer),
new Subscriber\TestErroredSubscriber($printer),
new Subscriber\TestSkippedSubscriber($printer),
new Subscriber\TestMarkedIncompleteSubscriber($printer),
new Subscriber\TestFinishedSubscriber($printer),
);
}
}
```
--------------------------------
### Framework Deprecation Trigger Example
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/error-handling.md
An example of a framework method that wraps `trigger_error()`. This demonstrates a scenario where a custom resolver might be needed.
```php
namespace Vendor;
final class Framework
{
public function trigger(): void
{
@trigger_error('framework deprecation', E_USER_DEPRECATED);
}
}
```
--------------------------------
### Set $_GET Variable with
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/xml-configuration-file.md
Use the `` element to set a value in the `$_GET` super-global array. Corresponds to `$_GET['foo'] = 'bar';`.
```xml
```
```php
$_GET['foo'] = 'bar';
```
--------------------------------
### Run All Tests with Configuration
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/textui.md
Execute all configured test suites by simply running the 'phpunit' command when a 'phpunit.xml' configuration file is present in the current working directory.
```shell
$ ./tools/phpunit
PHPUnit 13.2.0 by Sebastian Bergmann and contributors.
Runtime: PHP 8.5.3
Configuration: /path/to/project/phpunit.xml
.. 2 / 2 (100%)
Time: 00:00.077, Memory: 10.00 MB
OK (2 tests, 2 assertions)
```
--------------------------------
### Instantiate System Under Test with Stub
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/test-doubles.md
Instantiate the class you are testing (System Under Test) by injecting the created test stub. This ensures the SUT uses the controlled dependency.
```php
$service = new Service($database);
```
--------------------------------
### Example Test Execution Output
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/attributes.md
This output demonstrates a typical test run with failures, showing the command used, PHPUnit version, runtime information, test progress, and specific failure details including the assertion that failed and the file/line number.
```text
./tools/phpunit tests/DataTest.php
PHPUnit 13.2.0 by Sebastian Bergmann and contributors.
Runtime: PHP 8.2.2
...F 4 / 4 (100%)
Time: 00:00.058, Memory: 8.00 MB
There was 1 failure:
1) DataTest::testAdd with data set #3
Failed asserting that 2 is identical to 3.
/path/to/DataTest.php:10
FAILURES!
Tests: 4, Assertions: 4, Failures: 1.
```
--------------------------------
### Implement PHPUnit Extension
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/extending-phpunit.md
Implement the `Extension` interface to create a custom PHPUnit extension. The `bootstrap` method receives configuration, a facade, and parameters to customize extension behavior. Use the facade to register subscribers and tracers.
```php
noOutput()) {
return;
}
$message = 'the-default-message';
if ($parameters->has('message')) {
$message = $parameters->get('message');
}
$facade->registerSubscriber(new ExampleSubscriber($message));
$facade->registerTracer(new ExampleTracer);
}
}
```
--------------------------------
### assertEquals() with DateTimeInterface objects
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/assertions.md
Compares two DateTimeInterface objects for equality. This example shows a failure case where the times differ.
```PHP
assertEquals($expected, $actual);
}
}
```
--------------------------------
### PHPUnit Test Execution Output
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/writing-tests-for-phpunit.md
This is an example of the output generated when running tests with dependencies, showing successful execution and assertions.
```none
./tools/phpunit tests/StackTest.php
PHPUnit 13.2.0 by Sebastian Bergmann and contributors.
Runtime: PHP 8.5.7
... 3 / 3 (100%)
Time: 00:00.001, Memory: 28.00 MB
OK (3 tests, 5 assertions)
```
--------------------------------
### Create a Configured Mock Object
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/test-doubles.md
Use `createConfiguredMock()` for a convenience method to create a mock object with methods already configured to return specific values. Useful for simple cases.
```php
$mock = $this->createConfiguredMock(
InterfaceName::class,
[
'methodOne' => 'return value one',
'methodTwo' => 'return value two',
]
);
// $mock->methodOne() will return "return value one"
// $mock->methodTwo() will return "return value two"
```
--------------------------------
### assertEqualsIgnoringCase() Failure Example
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/assertions.md
Shows a failure case for assertEqualsIgnoringCase() when comparing strings with different casing. This assertion ignores case differences.
```php
assertEqualsIgnoringCase('foo', 'BAR');
}
}
```
```none
./tools/phpunit tests/EqualsWithStringsIgnoringCaseTest.php
PHPUnit 13.2.0 by Sebastian Bergmann and contributors.
Runtime: PHP 8.5.7
F 1 / 1 (100%)
Time: 00:00, Memory: 28.00 MB
There was 1 failure:
1) EqualsWithStringsIgnoringCaseTest::testFailure
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'foo'
+'BAR'
/path/to/tests/EqualsWithStringsIgnoringCaseTest.php:8
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
```
--------------------------------
### List Available Test Suites in PHPUnit XML
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/organizing-tests.md
Use the `--list-suites` option to display all test suites defined in your `phpunit.xml` configuration file.
```none
$ ./tools/phpunit --list-suites
PHPUnit 13.2.0 by Sebastian Bergmann and contributors.
Available test suite(s):
- unit
- integration
```
--------------------------------
### assertEqualsCanonicalizing() Failure Example
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/assertions.md
Illustrates a failure with assertEqualsCanonicalizing() when comparing arrays with different orders or elements. This method sorts arrays before comparison.
```php
assertEqualsCanonicalizing([3, 2, 1], [2, 3, 0, 1]);
}
}
```
```none
./tools/phpunit tests/EqualsWithArraysCanonicalizingTest.php
PHPUnit 13.2.0 by Sebastian Bergmann and contributors.
Runtime: PHP 8.5.7
F 1 / 1 (100%)
Time: 00:00, Memory: 28.00 MB
There was 1 failure:
1) EqualsWithArraysCanonicalizingTest::testFailure
Failed asserting that two arrays are equal.
--- Expected
+++ Actual
@@ @@
Array (
0
1
2
3
)
/path/to/tests/EqualsWithArraysCanonicalizingTest.php:8
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
```
--------------------------------
### Create Configured Stub
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/test-doubles.md
A convenience method to create a test stub with pre-configured method return values. Ideal for simple stubbing scenarios.
```php
$stub = $this->createConfiguredStub(
InterfaceName::class,
[
'methodOne' => 'return value one',
'methodTwo' => 'return value two',
]
);
// $stub->methodOne() will return "return value one"
// $stub->methodTwo() will return "return value two"
```
--------------------------------
### List tests in XML format
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/textui.md
Use the `--list-tests-xml` option to output a list of all tests that would be executed in XML format to a specified file.
```bash
phpunit --list-tests-xml output.xml
```
--------------------------------
### EmailTest Class Example
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/writing-tests-for-phpunit.md
This test class verifies the functionality of the Email class. It includes tests for valid and invalid email creation.
```php
assertSame($string, $email->asString());
}
public function testCannotBeCreatedFromInvalidEmail(): void
{
$this->expectException(InvalidArgumentException::class);
Email::fromString('invalid');
}
}
```
--------------------------------
### Asserting Variable is a List
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/assertions.md
Use assertIsList() to verify if an array has consecutive numeric keys starting from 0. This checks for a list-like structure.
```php
assertIsList([1 => 'foo', '3' => 'bar']);
}
}
```
--------------------------------
### Phive Configuration File
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/installation.md
The `.phive/phars.xml` file stores metadata about your project's tool dependencies, including version constraints and installation locations.
```xml
```
--------------------------------
### GreeterTest Class for TestDox
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/testdox.md
A PHPUnit test class demonstrating how TestDox formats method names into human-readable documentation.
```php
assertSame('Hello, World!', $greeter->greet('World'));
}
public function testGreetsWithGoodMorningBeforeNoon(): void
{
$greeter = new Greeter;
$this->assertSame(
'Good morning, Alice!',
$greeter->greetWithTimeOfDay('Alice', 9),
);
}
public function testGreetsWithGoodAfternoonAfterNoon(): void
{
$greeter = new Greeter;
$this->assertSame(
'Good afternoon, Alice!',
$greeter->greetWithTimeOfDay('Alice', 14),
);
}
public function testGreetsWithGoodEveningAfter6Pm(): void
{
$greeter = new Greeter;
$this->assertSame(
'Good evening, Alice!',
$greeter->greetWithTimeOfDay('Alice', 20),
);
}
}
```
--------------------------------
### Generate Baseline File
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/error-handling.md
Use the `--generate-baseline` CLI option to write a list of all triggered issues to an XML file.
```bash
$ phpunit --generate-baseline baseline.xml
PHPUnit 11.1.0 by Sebastian Bergmann and contributors.
Runtime: PHP 8.2.10
Configuration: /path/to/example/phpunit.xml
D 1 / 1 (100%)
Time: 00:00.008, Memory: 4.00 MB
OK, but there were issues!
Tests: 1, Assertions: 1, Deprecations: 1.
Baseline written to /path/to/example/baseline.xml.
```
--------------------------------
### PHPUnit assertStringMatchesFormat() Example
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/assertions.md
Demonstrates a failure case for `assertStringMatchesFormat()`. This assertion checks if a string matches a given format string, which can include placeholders.
```php
assertStringMatchesFormat('%i', 'foo');
}
}
```
--------------------------------
### PHPUnit assertLessThanOrEqual Example
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/assertions.md
Use this assertion to check if the actual value is less than or equal to the expected value. The test fails if the condition is not met.
```php
assertLessThanOrEqual(1, 2);
}
}
```
--------------------------------
### Create a Basic Mock Object
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/test-doubles.md
Use `createMock()` to generate a mock for a specified interface or extendable class. All methods can be configured with return values and expectations.
```php
$mock = $this->createMock(InterfaceName::class);
```
--------------------------------
### PHPUnit Template Method Execution Order
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/fixtures.md
Illustrates the lifecycle of a PHPUnit test case class, showing the order in which template methods like setUpBeforeClass(), setUp(), assertPreConditions(), test method, assertPostConditions(), tearDown(), and tearDownAfterClass() are executed.
```none
setUpBeforeClass() Once before the first test of the class
├── setUp() Before each test
│ ├── assertPreConditions()
│ │ ├── test method
│ │ assertPostConditions()
│ tearDown() After each test
tearDownAfterClass() Once after the last test of the class
```
--------------------------------
### PHPUnit assertLessThan Example
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/assertions.md
Use this assertion to check if the actual value is strictly less than the expected value. The test fails if the condition is not met.
```php
assertLessThan(1, 2);
}
}
```
--------------------------------
### Use Baseline File to Ignore Issues
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/error-handling.md
Use the `--use-baseline` CLI option to ignore previously known issues during the current test run. This can also be configured in the XML configuration file.
```bash
$ phpunit --use-baseline baseline.xml
PHPUnit 11.1.0 by Sebastian Bergmann and contributors.
Runtime: PHP 8.2.10
Configuration: /path/to/example/phpunit.xml
. 1 / 1 (100%)
Time: 00:00.007, Memory: 4.00 MB
OK (1 test, 1 assertion)
2 issues were ignored by baseline.
```
--------------------------------
### PHPUnit assertGreaterThanOrEqual Example
Source: https://github.com/sebastianbergmann/phpunit-documentation-english/blob/13.2/src/assertions.md
Use this assertion to check if the actual value is greater than or equal to the expected value. The test fails if the condition is not met.
```php
assertGreaterThanOrEqual(2, 1);
}
}
```