### PHPUnit Test Class with setUp() and tearDown() Source: https://docs.phpunit.de/en/13.0/fixtures.html This example demonstrates a basic PHPUnit test class that utilizes the setUp() method to initialize a test fixture and tearDown() to clean it up after each test method. ```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; } } ``` -------------------------------- ### Subclass Setup with Attributes Source: https://docs.phpunit.de/en/13.0/fixtures.html Shows how a subclass can define its own #[Before] setup method without needing to explicitly call the parent class's setup method. Both parent and subclass setup methods are executed. ```php noOutput()) { return; } $message = 'the-default-message'; if ($parameters->has('message')) { $message = $parameters->get('message'); } $facade->registerSubscriber(new ExampleSubscriber($message)); $facade->registerTracer(new ExampleTracer); } } ``` -------------------------------- ### Install PHPUnit with Phive Source: https://docs.phpunit.de/en/13.0/installation.html Install PHPUnit for your project using Phive. This command downloads the PHPUnit PHAR and sets up a symbolic link. ```bash phive install phpunit ``` -------------------------------- ### Test Stub Example: Configuring Return Values Source: https://docs.phpunit.de/en/13.0/test-doubles.html This example demonstrates how to create and configure a test stub for a Database dependency to simulate query results. It's used when you need to control what a dependency returns to test specific code paths in the System Under Test. ```php createStub(Database::class); $database ->method('query') ->willReturn([['foo' => 'bar']]); $service = new Service($database); $this->assertTrue($service->doSomething()); } } ``` -------------------------------- ### Install PHPUnit with Copy Option Source: https://docs.phpunit.de/en/13.0/installation.html Install PHPUnit using Phive and the --copy option to keep the PHAR file within the project's tools directory. ```bash phive install --copy phpunit ``` -------------------------------- ### Concrete Test Class Extending Abstract with setUp() Source: https://docs.phpunit.de/en/13.0/fixtures.html A concrete PHPUnit test class that extends an abstract test case class which has its own setUp() method. It's crucial to call parent::setUp() if overriding setUp() to ensure inherited setup logic is executed. ```php assertStringStartsWith('prefix', 'foo'); } } ``` -------------------------------- ### Abstract Test Case Class with setUp() Source: https://docs.phpunit.de/en/13.0/fixtures.html An abstract test case class in PHPUnit that defines a setUp() method. This method can be extended by concrete test classes. ```php 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" ``` -------------------------------- ### PHPUnit assertStringMatchesFormatFile Example Source: https://docs.phpunit.de/en/13.0/assertions.html Use assertStringMatchesFormatFile to compare a string against the content of a format file. This example illustrates a failing test scenario. ```php assertStringMatchesFormatFile( __DIR__ . '/expected-format.txt', 'foo', ); } } ``` -------------------------------- ### assertStringStartsWith Source: https://docs.phpunit.de/en/13.0/assertions.html Reports an error if the string does not start with the specified prefix. The inverse assertion is `assertStringStartsNotWith()`. ```APIDOC ## assertStringStartsWith() ### Description Reports an error if the `$string` does not start with `$prefix`. ### Method `assertStringStartsWith(string $prefix, string $string[, string $message])` ### Parameters - **prefix** (string) - Required - The prefix to check for. - **string** (string) - Required - The string to check. - **message** (string) - Optional - The message to report on failure. ### Related Assertions - `assertStringStartsNotWith()` ``` -------------------------------- ### TestDox Plain Text Output Example Source: https://docs.phpunit.de/en/13.0/testdox.html Example of plain text output from TestDox. Successful tests are marked with [x] and failed tests with [ ]. ```text 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 ``` -------------------------------- ### Tap PHP Formulae on macOS Source: https://docs.phpunit.de/en/13.0/installation.html Adds the necessary Homebrew repositories for installing PHP and its extensions on macOS. ```bash brew tap shivammathur/php brew tap shivammathur/extensions ``` -------------------------------- ### PHAR Manifest Example Source: https://docs.phpunit.de/en/13.0/extending-phpunit.html An example PHAR manifest.xml file required for making a PHPUnit extension loadable as a PHAR. It specifies package details, compatibility, and licensing. ```xml ``` -------------------------------- ### PHPUnit PHAR Configuration Source: https://docs.phpunit.de/en/13.0/installation.html Example of a phive configuration file specifying the PHPUnit version constraint. ```xml ``` -------------------------------- ### Check PHPUnit Version Source: https://docs.phpunit.de/en/13.0/installation.html Verify the installed PHPUnit version by running the downloaded PHAR file with the --version flag. ```bash php phpunit.phar --version ``` -------------------------------- ### Verify PHP Version Source: https://docs.phpunit.de/en/13.0/installation.html Checks if the PHP command-line interpreter is installed, on the system's PATH, and displays its version. ```bash php --version ``` -------------------------------- ### Example Event Subscriber Implementation Source: https://docs.phpunit.de/en/13.0/extending-phpunit.html This subscriber implements the `ExecutionFinishedSubscriber` interface. It prints a custom message when PHPUnit finishes execution, demonstrating how to react to specific events. ```php message . PHP_EOL; } } ``` -------------------------------- ### PHPUnit Test Execution Output Source: https://docs.phpunit.de/en/13.0/textui.html Example output from running a PHPUnit test that fails due to weak comparison differences. ```text ./tools/phpunit tests/ArrayWeakComparisonTest.php PHPUnit 13.0.0 by Sebastian Bergmann and contributors. Runtime: PHP 8.5.4 F 1 / 1 (100%) Time: 00:00.001, Memory: 25.94 MB There was 1 failure: 1) ArrayWeakComparisonTest::testEquality Failed asserting that two arrays are equal. --- Expected +++ Actual @@ @@ Array ( - 0 => 1 + 0 => '1' 1 => 2 - 2 => 3 + 2 => 33 3 => 4 4 => 5 5 => 6 ) /path/to/tests/ArrayWeakComparisonTest.php:8 FAILURES! Tests: 1, Assertions: 1, Failures: 1. ``` -------------------------------- ### Set GET Variable with Source: https://docs.phpunit.de/en/13.0/configuration.html Use the element to set a value in the $_GET super-global array. ```xml ``` ```php $_GET['foo'] = 'bar'; ``` -------------------------------- ### Using assertPreConditions() and assertPostConditions() Source: https://docs.phpunit.de/en/13.0/fixtures.html Demonstrates how to use assertPreConditions() and assertPostConditions() to verify fixture state before and after test execution. These methods are called after setUp() and before tearDown(), respectively, and failures are reported as test failures. ```php object = new SomeObject; } protected function assertPreConditions(): void { $this->assertTrue($this->object->isReady()); } protected function assertPostConditions(): void { $this->assertFalse($this->object->hasErrors()); } protected function tearDown(): void { $this->object = null; } public function testSomething(): void { $this->object->doSomething(); $this->assertSame('expected', $this->object->result()); } } ``` -------------------------------- ### Install Xdebug Extension on macOS Source: https://docs.phpunit.de/en/13.0/installation.html Installs and enables the Xdebug extension for debugging on macOS. ```bash brew install xdebug@8.4 ``` -------------------------------- ### Using #[Before] and #[After] Attributes Source: https://docs.phpunit.de/en/13.0/fixtures.html Illustrates using PHP attributes like #[Before] and #[After] as alternatives to template methods for setting up and tearing down fixtures. This allows for multiple setup/teardown methods per phase, especially useful in class hierarchies. ```php assertStringMatchesFormat('%i', 'foo'); } } ``` -------------------------------- ### PHPUnit assertInstanceOf() Example Source: https://docs.phpunit.de/en/13.0/assertions.html Use assertInstanceOf() to check if a variable is an instance of a specific class. This example shows a test designed to fail. ```php assertInstanceOf(RuntimeException::class, new Exception); } } ``` -------------------------------- ### PHPUnit assertLessThanOrEqual() Example Source: https://docs.phpunit.de/en/13.0/assertions.html Use assertLessThanOrEqual() to ensure a value is less than or equal to an expected value. This example illustrates a failing assertion. ```php assertLessThanOrEqual(1, 2); } } ``` -------------------------------- ### PHPUnit assertMatchesRegularExpression Example Source: https://docs.phpunit.de/en/13.0/assertions.html Use assertMatchesRegularExpression to check if a string matches a given PCRE pattern. This example demonstrates a failing test case. ```php assertMatchesRegularExpression('/foo/', 'bar'); } } ``` -------------------------------- ### Instantiate System Under Test with Mock Dependency Source: https://docs.phpunit.de/en/13.0/test-doubles.html Creates an instance of ServiceImplementation, injecting the configured mock ErrorHandler. This allows testing the service in isolation. ```php $service = new ServiceImplementation($errorHandler); ``` -------------------------------- ### PHPUnit assertGreaterThanOrEqual() Example Source: https://docs.phpunit.de/en/13.0/assertions.html Use assertGreaterThanOrEqual() to check if a value is greater than or equal to an expected value. This example demonstrates a failing test case. ```php assertGreaterThanOrEqual(2, 1); } } ``` -------------------------------- ### Implement PHPUnit Extension Entry Point Source: https://docs.phpunit.de/en/13.0/extending-phpunit.html This class implements the `PHPUnit\Runner\Extension\Extension` interface, defining the `bootstrap()` method to register custom output and event subscribers with PHPUnit's facade. ```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), ); } } ``` -------------------------------- ### Using createStub() as an Alternative to any() Source: https://docs.phpunit.de/en/13.0/test-doubles.html When you only need to control return values without verifying call counts, `createStub()` is the preferred method over `createMock()` with `any()`. This avoids the contradiction of mocking communication while ignoring it. ```php $stub = $this->createStub(InterfaceName::class); $stub ->method('doSomething') ->willReturn('value'); ``` -------------------------------- ### Create Configured Mock Object Source: https://docs.phpunit.de/en/13.0/test-doubles.html Creates a mock object with predefined return values for specific methods. This is a convenient way to set up mocks for simple scenarios. ```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" ``` -------------------------------- ### Share Database Connection with setUpBeforeClass and tearDownAfterClass Source: https://docs.phpunit.de/en/13.0/fixtures.html Connect to an in-memory SQLite database before the first test and disconnect after the last test in a test case class. This method is useful for performance optimization when a resource is expensive to set up. ```php assertFileEquals( __DIR__ . '/expected.txt', __DIR__ . '/actual.txt', ); } } ``` -------------------------------- ### ExampleTracer Implementation Source: https://docs.phpunit.de/en/13.0/extending-phpunit.html Implement the PHPUnit\Event\Tracer\Tracer interface to create a custom event tracer. This tracer will receive all events emitted by PHPUnit. ```php ``` -------------------------------- ### Interface with a get-hooked property Source: https://docs.phpunit.de/en/13.0/test-doubles.html Example of an interface declaring a get-hooked property, introduced in PHP 8.4. ```PHP assertGreaterThan(2, 1); } } ``` -------------------------------- ### Using assertThat() with logicalNot() and equalTo() Source: https://docs.phpunit.de/en/13.0/assertions.html This example demonstrates how to use assertThat() with logicalNot() and equalTo() constraints to express an assertion equivalent to assertNotEquals(). It requires the PHPUnit TestCase class. ```PHP assertThat( $theBiscuit, $this->logicalNot( $this->equalTo($myBiscuit), ), ); } } ``` -------------------------------- ### PHPUnit assertEmpty() Example Source: https://docs.phpunit.de/en/13.0/assertions.html Use assertEmpty() to assert that a variable or structure is empty. This assertion does not support generators. ```php assertEmpty(['foo']); } } ``` -------------------------------- ### Registering Extension from PHAR with Parameters Source: https://docs.phpunit.de/en/13.0/extending-phpunit.html Configure PHPUnit to load extensions from a PHAR file located in a specified directory. This example shows how to set the extensionsDirectory attribute and register an extension with a parameter. ```xml ```