### Using setUp() for Stack Fixture in PHPUnit Source: https://docs.phpunit.de/en/9.6/fixtures.html This example demonstrates how to use the `setUp()` method to create a common fixture for multiple test methods. The `$stack` array is initialized before each test, ensuring a clean state. Use this when tests require a similar initial setup. ```php stack = []; } public function testEmpty(): void { $this->assertTrue(empty($this->stack)); } public function testPush(): void { array_push($this->stack, 'foo'); $this->assertSame('foo', $this->stack[count($this->stack)-1]); $this->assertFalse(empty($this->stack)); } public function testPop(): void { array_push($this->stack, 'foo'); $this->assertSame('foo', array_pop($this->stack)); $this->assertTrue(empty($this->stack)); } } ``` -------------------------------- ### PHPUnit Template Methods Example Source: https://docs.phpunit.de/en/9.6/fixtures.html This example showcases all available template methods in a PHPUnit test case class, including `setUpBeforeClass()`, `setUp()`, `assertPreConditions()`, `testOne()`, `testTwo()`, `assertPostConditions()`, `tearDown()`, `tearDownAfterClass()`, and `onNotSuccessfulTest()`. These methods allow for comprehensive control over test execution lifecycle. ```php assertTrue(true); } public function testTwo(): void { fwrite(STDOUT, __METHOD__ . "\n"); $this->assertTrue(false); } protected function assertPostConditions(): void { fwrite(STDOUT, __METHOD__ . "\n"); } protected function tearDown(): void { fwrite(STDOUT, __METHOD__ . "\n"); } public static function tearDownAfterClass(): void { fwrite(STDOUT, __METHOD__ . "\n"); } protected function onNotSuccessfulTest(Throwable $t): void { fwrite(STDOUT, __METHOD__ . "\n"); throw $t; } } ``` -------------------------------- ### PHPUnit Installation Source: https://docs.phpunit.de/en/9.6/organizing-tests.html Instructions and requirements for installing PHPUnit. ```APIDOC ## PHPUnit Installation ### Requirements - Prophecy ### Installation Methods - PHP Archive (PHAR) - PHAR Implementation Details - Verifying PHPUnit PHAR Releases - Composer - Global Installation ### Webserver Configuration ``` -------------------------------- ### assertStringStartsWith() Source: https://docs.phpunit.de/en/9.6/assertions.html Asserts that a string starts with a specified prefix. ```APIDOC ## assertStringStartsWith() ### Description Reports an error if the provided string does not start with the specified prefix. ### Parameters - **$prefix** (string) - Required - The expected prefix. - **$string** (string) - Required - The string to be tested. - **$message** (string) - Optional - Custom error message to display on failure. ### Request Example $this->assertStringStartsWith('prefix', 'foo'); ``` -------------------------------- ### Install PHPUnit via Composer Source: https://docs.phpunit.de/en/9.6/installation.html Add PHPUnit as a development dependency to a project using Composer. ```bash composer require --dev phpunit/phpunit ^9.6 ``` -------------------------------- ### Define @before setup methods Source: https://docs.phpunit.de/en/9.6/annotations.html Use the @before annotation to mark methods that execute before every test method in the class. ```php tests/unit tests/integration tests/edge-to-edge ``` -------------------------------- ### CLI output for assertObjectEquals failure Source: https://docs.phpunit.de/en/9.6/assertions.html Example output when an object equality assertion fails. ```bash $ phpunit EqualsTest PHPUnit 9.6.0 by Sebastian Bergmann and contributors. F 1 / 1 (100%) Time: 00:00.017, Memory: 4.00 MB There was 1 failure: 1) SomethingThatUsesEmailTest::testSomething Failed asserting that two objects are equal. The objects are not equal according to Email::equals(). /home/sb/SomethingThatUsesEmailTest.php:16 FAILURES! Tests: 1, Assertions: 2, Failures: 1. ``` -------------------------------- ### Using Prophecy with PHPUnit Source: https://docs.phpunit.de/en/9.6/test-doubles.html Example demonstrating how to use Prophecy for creating mock objects within PHPUnit tests. ```APIDOC ## Prophecy Integration with PHPUnit ### Description This example shows how to use Prophecy, a PHP object mocking framework, with PHPUnit to create and configure test doubles. It demonstrates setting expectations on method calls and revealing the mock object. ### Prerequisites - Add `phpspec/prophecy` as a dependency to your `composer.json`. - Note: PHPUnit's out-of-the-box support for Prophecy is deprecated as of PHPUnit 9.1.0 and will be removed in PHPUnit 10. Prophecy may not support PHP 8.2 as of August 2022. ### Request Example ```php prophesize(Observer::class); // Set up the expectation for the update() method // to be called only once and with the string 'something' // as its parameter. $observer->update('something')->shouldBeCalled(); // Reveal the prophecy and attach the mock object // to the Subject. $subject->attach($observer->reveal()); // Call the doSomething() method on the $subject object // which we expect to call the mocked Observer object's // update() method with the string 'something'. $subject->doSomething(); } } ``` ### Further Information Refer to the Prophecy documentation for more details on creating, configuring, and using stubs, spies, and mocks. ``` -------------------------------- ### PHPUnit Test Execution Output Source: https://docs.phpunit.de/en/9.6/fixtures.html This output demonstrates the order in which PHPUnit template methods are executed for a test class. It shows the calls to `setUpBeforeClass`, `setUp`, `assertPreConditions`, test methods, `assertPostConditions`, `tearDown`, and `tearDownAfterClass`, including the handling of a failed test via `onNotSuccessfulTest`. ```text $ phpunit TemplateMethodsTest PHPUnit 9.6.0 by Sebastian Bergmann and contributors. TemplateMethodsTest::setUpBeforeClass TemplateMethodsTest::setUp TemplateMethodsTest::assertPreConditions TemplateMethodsTest::testOne TemplateMethodsTest::assertPostConditions TemplateMethodsTest::tearDown .TemplateMethodsTest::setUp TemplateMethodsTest::assertPreConditions TemplateMethodsTest::testTwo TemplateMethodsTest::tearDown TemplateMethodsTest::onNotSuccessfulTest FTemplateMethodsTest::tearDownAfterClass Time: 0 seconds, Memory: 5.25Mb There was 1 failure: 1) TemplateMethodsTest::testTwo Failed asserting that is true. /home/sb/TemplateMethodsTest.php:30 ``` -------------------------------- ### Define @beforeClass setup methods Source: https://docs.phpunit.de/en/9.6/annotations.html Use the @beforeClass annotation to mark static methods that execute once before any test methods in the class run. ```php assertEquals(1, 0); } public function testFailure2(): void { $this->assertEquals('bar', 'baz'); } public function testFailure3(): void { $this->assertEquals("foo\nbar\nbaz\n", "foo\nbah\nbaz\n"); } } ``` -------------------------------- ### Share database fixture using setUpBeforeClass and tearDownAfterClass Source: https://docs.phpunit.de/en/9.6/fixtures.html Use these static methods to initialize and clean up expensive resources like database connections once per test class. ```php createStub(SomeClass::class); // Configure the stub. $stub->method('doSomething') ->will($this->throwException(new Exception)); // $stub->doSomething() throws Exception $stub->doSomething(); } } ``` -------------------------------- ### Handling Multiple Dependencies Source: https://docs.phpunit.de/en/9.6/writing-tests-for-phpunit.html Illustrates how a test method can consume return values from multiple producer tests. ```php assertTrue(true); return 'first'; } public function testProducerSecond(): string { $this->assertTrue(true); return 'second'; } /** * @depends testProducerFirst * @depends testProducerSecond */ public function testConsumer(string $a, string $b): void { $this->assertSame('first', $a); $this->assertSame('second', $b); } } ``` ```bash $ phpunit --verbose MultipleDependenciesTest PHPUnit 9.6.0 by Sebastian Bergmann and contributors. ... Time: 0 seconds, Memory: 3.25Mb OK (3 tests, 4 assertions) ``` -------------------------------- ### Set GET Super-global Source: https://docs.phpunit.de/en/9.6/configuration.html Sets a value in the $_GET super-global array. ```xml ``` ```php $_GET['foo'] = 'bar'; ``` -------------------------------- ### Usage of assertStringStartsWith() Source: https://docs.phpunit.de/en/9.6/assertions.html Demonstrates the implementation of assertStringStartsWith() within a PHPUnit test case. ```php assertStringStartsWith('prefix', 'foo'); } } ``` -------------------------------- ### Execution output of assertStringStartsWith() Source: https://docs.phpunit.de/en/9.6/assertions.html Shows the console output when the assertStringStartsWith() assertion fails. ```text $ phpunit StringStartsWithTest PHPUnit 9.6.0 by Sebastian Bergmann and contributors. F Time: 0 seconds, Memory: 5.00Mb There was 1 failure: 1) StringStartsWithTest::testFailure Failed asserting that 'foo' starts with "prefix". /home/sb/StringStartsWithTest.php:6 FAILURES! Tests: 1, Assertions: 1, Failures: 1. ``` -------------------------------- ### Generate TestDox Documentation in HTML or Text Source: https://docs.phpunit.de/en/9.6/textui.html Use the --testdox-html and --testdox-text arguments to generate agile documentation in HTML or plain text format, respectively, and write it to a file. ```bash $ phpunit --testdox-html documentation.html BankAccountTest.php $ phpunit --testdox-text documentation.txt BankAccountTest.php ``` -------------------------------- ### The XML Configuration File Source: https://docs.phpunit.de/en/9.6/organizing-tests.html Details on configuring PHPUnit using an XML configuration file. ```APIDOC ## The XML Configuration File ### The `` Element and its Attributes - `backupGlobals` - `backupStaticAttributes` - `bootstrap` - `cacheResult` - `cacheResultFile` - `colors` - `columns` - `convertDeprecationsToExceptions` - `convertErrorsToExceptions` - `convertNoticesToExceptions` - `convertWarningsToExceptions` - `forceCoversAnnotation` - `printerClass` - `printerFile` - `processIsolation` - `stopOnError` - `stopOnFailure` - `stopOnIncomplete` - `stopOnRisky` - `stopOnSkipped` - `stopOnWarning` - `stopOnDefect` - `failOnIncomplete` - `failOnRisky` - `failOnSkipped` - `failOnWarning` - `beStrictAboutChangesToGlobalState` - `beStrictAboutOutputDuringTests` ``` -------------------------------- ### Usage of assertFileEquals() Source: https://docs.phpunit.de/en/9.6/assertions.html Demonstrates comparing the contents of two files. ```php assertFileEquals('/home/sb/expected', '/home/sb/actual'); } } ``` -------------------------------- ### Run Test Suite by Name Source: https://docs.phpunit.de/en/9.6/organizing-tests.html Execute a test suite defined in the XML configuration file using the '--testsuite' option. This command runs the 'money' test suite. ```bash $ phpunit --bootstrap src/autoload.php --testsuite money PHPUnit 9.6.0 by Sebastian Bergmann and contributors. .. Time: 167 ms, Memory: 3.00Mb OK (2 test, 2 assertions) ``` -------------------------------- ### Filter test execution patterns Source: https://docs.phpunit.de/en/9.6/textui.html Examples of valid filter patterns for selecting specific tests or methods. ```bash --filter 'TestNamespace\\TestCaseClass::testMethod' --filter 'TestNamespace\\TestCaseClass' --filter TestNamespace --filter TestCaseClass --filter testMethod --filter '/::testMethod .*"my named data"/' --filter '/::testMethod .*#5$/' --filter '/::testMethod .*#(5|6|7)$/' ``` -------------------------------- ### Define a Class for Stubbing Source: https://docs.phpunit.de/en/9.6/test-doubles.html This is a simple class that can be used as a target for stubbing in PHPUnit tests. No specific setup is required. ```php `** (string) - A PHP script that is included as early as possible. - **`--bootstrap `** (string) - A PHP script that is included before the tests run. - **`-c|--configuration `** (string) - Read configuration from XML file. - **`--no-configuration`** - Ignore default configuration file (phpunit.xml). - **`--extensions `** (string) - A comma separated list of PHPUnit extensions to load. - **`--no-extensions`** - Do not load PHPUnit extensions. - **`--include-path `** (string) - Prepend PHP's include_path with given path(s). - **`-d `** (string) - Sets a php.ini value. - **`--generate-configuration`** - Generate configuration file with suggested settings. - **`--migrate-configuration`** - Migrate configuration file to current format. ### Request Example ```bash phpunit -c phpunit.xml phpunit --bootstrap bootstrap.php phpunit -d memory_limit=256M ``` ### Response N/A (Output to console or log files) ``` -------------------------------- ### Import Release Manager Public Key Source: https://docs.phpunit.de/en/9.6/installation.html Import the public key required to verify the signature of the PHPUnit release. ```bash $ curl --silent https://sebastian-bergmann.de/gpg.asc | gpg --import gpg: key 4AA394086372C20A: 452 signatures not checked due to missing keys gpg: key 4AA394086372C20A: public key "Sebastian Bergmann " imported gpg: Total number processed: 1 gpg: imported: 1 gpg: no ultimately trusted keys found ``` -------------------------------- ### Define named data sets in PHPUnit Source: https://docs.phpunit.de/en/9.6/textui.html Example of using a data provider with named sets for test methods. ```php assertTrue($data); } public function provider() { return [ 'my named data' => [true], 'my data' => [true] ]; } } ``` -------------------------------- ### Assert directory readability with PHPUnit Source: https://docs.phpunit.de/en/9.6/assertions.html Verifies that a directory exists and is readable. ```php assertDirectoryIsReadable('/path/to/directory'); } } ``` ```bash $ phpunit DirectoryIsReadableTest PHPUnit 9.6.0 by Sebastian Bergmann and contributors. F Time: 0 seconds, Memory: 4.75Mb There was 1 failure: 1) DirectoryIsReadableTest::testFailure Failed asserting that "/path/to/directory" is readable. /home/sb/DirectoryIsReadableTest.php:6 FAILURES! Tests: 1, Assertions: 1, Failures: 1. ``` -------------------------------- ### Recommended PHP configuration for PHPUnit Source: https://docs.phpunit.de/en/9.6/installation.html Recommended settings for the php.ini file to ensure PHPUnit provides the most informative output during test runs. ```ini memory_limit=-1 error_reporting=-1 log_errors_max_len=0 zend.assertions=1 assert.exception=1 xdebug.show_exception_trace=0 ``` -------------------------------- ### Test exceptions with expectException Source: https://docs.phpunit.de/en/9.6/writing-tests-for-phpunit.html Illustrates the use of expectException to verify that specific exceptions are thrown during test execution. ```php expectException(InvalidArgumentException::class); } } ``` ```bash $ phpunit ExceptionTest PHPUnit 9.6.0 by Sebastian Bergmann and contributors. F Time: 0 seconds, Memory: 4.75Mb There was 1 failure: 1) ExceptionTest::testException Failed asserting that exception of type "InvalidArgumentException" is thrown. FAILURES! Tests: 1, Assertions: 1, Failures: 1. ``` -------------------------------- ### Asserting array equality with assertEquals() Source: https://docs.phpunit.de/en/9.6/assertions.html Use assertEquals() to check if two arrays are identical in terms of keys and values. This example demonstrates a failure case with differing array contents. ```PHP assertEquals(['a', 'b', 'c'], ['a', 'c', 'd']); } } ``` -------------------------------- ### Configure PHP INI Settings Source: https://docs.phpunit.de/en/9.6/configuration.html Sets PHP configuration settings equivalent to ini_set. ```xml ``` ```php ini_set('foo', 'bar'); ``` -------------------------------- ### Asserting object equality with assertEquals() Source: https://docs.phpunit.de/en/9.6/assertions.html Use assertEquals() to compare two objects for equal attribute values. This example shows a failure case where objects have different properties or values. ```PHP foo = 'foo'; $expected->bar = 'bar'; $actual = new stdClass; $actual->foo = 'bar'; $actual->baz = 'bar'; $this->assertEquals($expected, $actual); } } ``` -------------------------------- ### Asserting DOMDocument equality with assertEquals() Source: https://docs.phpunit.de/en/9.6/assertions.html Use assertEquals() to compare two DOMDocument objects based on their uncommented canonical form. This example demonstrates a failure case with different XML structures. ```PHP loadXML(''); $actual = new DOMDocument; $actual->loadXML(''); $this->assertEquals($expected, $actual); } } ``` -------------------------------- ### Skip a test if environment condition is not met Source: https://docs.phpunit.de/en/9.6/incomplete-and-skipped-tests.html Use `markTestSkipped()` in a setup method or test method to skip a test if certain conditions, like the availability of an extension, are not met. This is useful for tests that depend on specific environment configurations. ```PHP markTestSkipped( 'The MySQLi extension is not available.' ); } } public function testConnection(): void { // ... } } ``` -------------------------------- ### Generate TestDox Documentation Source: https://docs.phpunit.de/en/9.6/textui.html Use the --testdox argument to generate agile documentation from test methods. This command processes the specified test file and outputs the results in a human-readable format. ```bash $ phpunit --testdox BankAccountTest.php ``` -------------------------------- ### Test Observer ReportError with Argument Constraints Source: https://docs.phpunit.de/en/9.6/test-doubles.html This example shows how to test the `reportError()` method of an Observer mock object with advanced argument constraints. It uses `greaterThan()`, `stringContains()`, and `anything()` to define flexible expectations for the arguments passed to the mocked method. ```php createMock(Observer::class); $observer->expects($this->once()) ->method('reportError') ->with( $this->greaterThan(0), $this->stringContains('Something'), $this->anything() ); $subject = new Subject('My subject'); ``` -------------------------------- ### Test with Named Datasets Source: https://docs.phpunit.de/en/9.6/writing-tests-for-phpunit.html Demonstrates using named datasets in a data provider for more descriptive test output. String keys are used for each dataset. ```php assertSame($expected, $a + $b); } public function additionProvider(): array { return [ 'adding zeros' => [0, 0, 0], 'zero plus one' => [0, 1, 1], 'one plus zero' => [1, 0, 1], 'one plus one' => [1, 1, 3] ]; } } ``` -------------------------------- ### Configure Code Coverage Settings Source: https://docs.phpunit.de/en/9.6/configuration.html Set up code coverage analysis, including the directory for caching results and options for including and processing uncovered files. ```xml ``` -------------------------------- ### Configure Extension Arguments Source: https://docs.phpunit.de/en/9.6/configuration.html Defines arguments passed to an extension class constructor in the order specified. ```xml 1 2 3 hello world true 1.23 value1 value2 constructor arg 1 constructor arg 2 ``` -------------------------------- ### The Command-Line Test Runner Source: https://docs.phpunit.de/en/9.6/organizing-tests.html How to use the PHPUnit command-line interface to run tests. ```APIDOC ## The Command-Line Test Runner ### Command-Line Options - Detailed explanation of available options. ### TestDox - Using TestDox for human-readable test output. ``` -------------------------------- ### Assert directory writability with PHPUnit Source: https://docs.phpunit.de/en/9.6/assertions.html Verifies that a directory exists and is writable. ```php assertDirectoryIsWritable('/path/to/directory'); } } ``` ```bash $ phpunit DirectoryIsWritableTest PHPUnit 9.6.0 by Sebastian Bergmann and contributors. F Time: 0 seconds, Memory: 4.75Mb There was 1 failure: 1) DirectoryIsWritableTest::testFailure Failed asserting that "/path/to/directory" is writable. /home/sb/DirectoryIsWritableTest.php:6 FAILURES! Tests: 1, Assertions: 1, Failures: 1. ``` -------------------------------- ### PHPUnit Command-Line Options Source: https://docs.phpunit.de/en/9.6/textui.html This section lists and describes the available command-line options for the PHPUnit test runner. ```APIDOC ## PHPUnit Command-Line Options This document outlines the various command-line options available for the PHPUnit test runner. ### Usage ``` phpunit [options] UnitTest.php phpunit [options] ``` ### Code Coverage Options - `--coverage-clover `: Generate code coverage report in Clover XML format. - `--coverage-crap4j `: Generate code coverage report in Crap4J XML format. - `--coverage-html `: Generate code coverage report in HTML format. - `--coverage-php `: Export PHP_CodeCoverage object to file. - `--coverage-text=`: Generate code coverage report in text format [default: standard output]. - `--coverage-xml `: Generate code coverage report in PHPUnit XML format. - `--coverage-cache `: Cache static analysis results. - `--warm-coverage-cache`: Warm static analysis cache. - `--coverage-filter `: Include `` in code coverage analysis. - `--path-coverage`: Perform path coverage analysis. - `--disable-coverage-ignore`: Disable annotations for ignoring code coverage. - `--no-coverage`: Ignore code coverage configuration. ### Logging Options - `--log-junit `: Log test execution in JUnit XML format to file. - `--log-teamcity `: Log test execution in TeamCity format to file. - `--testdox-html `: Write agile documentation in HTML format to file. - `--testdox-text `: Write agile documentation in Text format to file. - `--testdox-xml `: Write agile documentation in XML format to file. - `--reverse-list`: Print defects in reverse order. - `--no-logging`: Ignore logging configuration. ### Test Selection Options - `--filter `: Filter which tests to run. - `--testsuite `: Filter which testsuite to run. - `--group `: Only runs tests from the specified group(s). - `--exclude-group `: Exclude tests from the specified group(s). - `--list-groups`: List available test groups. - `--list-suites`: List available test suites. - `--list-tests`: List available tests. - `--list-tests-xml `: List available tests in XML format. - `--test-suffix `: Only search for test in files with specified suffix(es). Default: Test.php,.phpt ### Test Execution Options - `--dont-report-useless-tests`: Do not report tests that do not test anything. - `--strict-coverage`: Be strict about @covers annotation usage. - `--strict-global-state`: Be strict about changes to global state. - `--disallow-test-output`: Be strict about output during tests. - `--disallow-resource-usage`: Be strict about resource usage during small tests. - `--enforce-time-limit`: Enforce time limit based on test size. - `--default-time-limit `: Timeout in seconds for tests without @small, @medium or @large. - `--disallow-todo-tests`: Disallow @todo-annotated tests. - `--process-isolation`: Run each test in a separate PHP process. - `--globals-backup`: Backup and restore $GLOBALS for each test. - `--static-backup`: Backup and restore static attributes for each test. - `--colors `: Use colors in output ("never", "auto" or "always"). - `--columns `: Number of columns to use for progress output. - `--columns max`: Use maximum number of columns for progress output. - `--stderr`: Write to STDERR instead of STDOUT. - `--stop-on-defect`: Stop execution upon first not-passed test. - `--stop-on-error`: Stop execution upon first error. - `--stop-on-failure`: Stop execution upon first error or failure. - `--stop-on-warning`: Stop execution upon first warning. - `--stop-on-risky`: Stop execution upon first risky test. - `--stop-on-skipped`: Stop execution upon first skipped test. - `--stop-on-incomplete`: Stop execution upon first incomplete test. - `--fail-on-incomplete`: Treat incomplete tests as failures. - `--fail-on-risky`: Treat risky tests as failures. - `--fail-on-skipped`: Treat skipped tests as failures. - `--fail-on-warning`: Treat tests with warnings as failures. - `-v|--verbose`: Output more verbose information. - `--debug`: Display debugging information. - `--repeat `: Runs the test(s) repeatedly. - `--teamcity`: Report test execution progress in TeamCity format. - `--testdox`: Report test execution progress in TestDox format. - `--testdox-group`: Only include tests from the specified group(s). - `--testdox-exclude-group`: Exclude tests from the specified group(s). - `--no-interaction`: Disable TestDox progress animation. - `--printer `: TestListener implementation to use. - `--order-by `: Run tests in order: default|defects|duration|no-depends|random|reverse|size. - `--random-order-seed `: Use a specific random seed for random order. ``` -------------------------------- ### Running PHPUnit tests via CLI Source: https://docs.phpunit.de/en/9.6/writing-tests-for-phpunit.html Execute tests from the command line to verify the test suite output. ```bash $ phpunit ErrorSuppressionTest PHPUnit 9.6.0 by Sebastian Bergmann and contributors. . Time: 1 seconds, Memory: 5.25Mb OK (1 test, 1 assertion) ``` -------------------------------- ### Enable Argument Cloning for Mock Objects Source: https://docs.phpunit.de/en/9.6/test-doubles.html Demonstrates how to enable argument cloning for a mock object. When enabled, the mock object clones parameters passed to its methods, which can affect constraints like identicalTo. ```PHP getMockBuilder(stdClass::class) ->enableArgumentCloning() ->getMock(); // now your mock clones parameters so the identicalTo constraint // will fail. } } ``` -------------------------------- ### Configure @backupGlobals at method level Source: https://docs.phpunit.de/en/9.6/annotations.html Override global variable backup settings for individual test methods within a class. ```php tests ``` -------------------------------- ### Verify file existence with assertFileExists Source: https://docs.phpunit.de/en/9.6/assertions.html Checks if a file exists at the specified path. Fails if the file is missing. ```php assertFileExists('/path/to/file'); } } ``` ```bash $ phpunit FileExistsTest PHPUnit 9.6.0 by Sebastian Bergmann and contributors. F Time: 0 seconds, Memory: 4.75Mb There was 1 failure: 1) FileExistsTest::testFailure Failed asserting that file "/path/to/file" exists. /home/sb/FileExistsTest.php:6 FAILURES! Tests: 1, Assertions: 1, Failures: 1. ``` -------------------------------- ### Writing Tests for PHPUnit Source: https://docs.phpunit.de/en/9.6/organizing-tests.html Guidelines and techniques for writing effective tests using PHPUnit. ```APIDOC ## Writing Tests for PHPUnit ### Core Concepts - Test Dependencies - Data Providers - Testing Exceptions - Testing PHP Errors, Warnings, and Notices - Testing Output (including Error Output) - Edge Cases ``` -------------------------------- ### Make PHPUnit PHAR executable Source: https://docs.phpunit.de/en/9.6/installation.html Change file permissions to allow direct execution of the PHAR file. ```bash $ curl -LO https://phar.phpunit.de/phpunit-9.6.phar $ chmod +x phpunit-9.6.phar $ ./phpunit-9.6.phar --version PHPUnit x.y.z by Sebastian Bergmann and contributors. ``` -------------------------------- ### Testing Output with expectOutputString Source: https://docs.phpunit.de/en/9.6/writing-tests-for-phpunit.html Use expectOutputString to verify that a method produces the exact expected string output. Tests will fail if the actual output does not match the expectation. ```php expectOutputString('foo'); print 'foo'; } public function testExpectBarActualBaz(): void { $this->expectOutputString('bar'); print 'baz'; } } ``` ```bash $ phpunit OutputTest PHPUnit 9.6.0 by Sebastian Bergmann and contributors. .F Time: 0 seconds, Memory: 5.75Mb There was 1 failure: 1) OutputTest::testExpectBarActualBaz Failed asserting that two strings are equal. --- Expected +++ Actual @@ @@ -'bar' +'baz' FAILURES! Tests: 2, Assertions: 2, Failures: 1. ```