### PHPUnit Stack Test Fixture with setUp() Source: https://docs.phpunit.de/en/8.5/fixtures Demonstrates using the setUp() method in PHPUnit to initialize a test fixture (an array representing a stack) before each test method runs. This avoids code duplication for fixture setup. The test methods then operate on the initialized fixture. ```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)); } } ``` -------------------------------- ### Recommended PHP Configuration for PHPUnit Source: https://docs.phpunit.de/en/8.5/installation This configuration should be set in the `php.ini` file to ensure PHPUnit's output is informative. It affects memory limits, error reporting, and assertion behavior. ```ini memory_limit=-1 error_reporting=-1 log_errors_max_len=0 zend.assertions=1 assert.exception=1 xdebug.show_exception_trace=0 ``` -------------------------------- ### Specify Class Coverage with @covers Annotation Source: https://docs.phpunit.de/en/8.5/code-coverage-analysis This example demonstrates how to use the @covers annotation at the class level to specify that the test class should cover the \Invoice class. It also shows the use of @uses to indicate dependency on \Money. The setUp method initializes an Invoice object, and testAmountInitiallyIsEmpty asserts its initial state. ```php invoice = new Invoice; } public function testAmountInitiallyIsEmpty(): void { $this->assertEquals(new Money, $this->invoice->getAmount()); } } ``` -------------------------------- ### Make PHPUnit PHAR Executable Source: https://docs.phpunit.de/en/8.5/installation This command sequence shows how to download the PHPUnit 8.5 PHAR, make it executable using `chmod +x`, and then run it directly to check its version. ```bash $ curl -LO https://phar.phpunit.de/phpunit-8.5.phar $ chmod +x phpunit-8.5.phar $ ./phpunit-8.5.phar --version ``` -------------------------------- ### Import Release Manager's Public Key Source: https://docs.phpunit.de/en/8.5/installation This snippet demonstrates how to import the public GPG key of the release manager. Importing the key is a necessary step to enable `gpg --verify` to check the signature against a known public key. ```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 ``` -------------------------------- ### PHPUnit Code Coverage Generation Source: https://docs.phpunit.de/en/8.5/textui Options for generating code coverage reports in various formats. These options require the tokenizer and Xdebug extensions to be installed and provide insights into code execution during tests. ```bash --coverage-clover # Generates a logfile in XML format with the code coverage information for the tests run. See Logging for more details. # Please note that this functionality is only available when the tokenizer and Xdebug extensions are installed. --coverage-crap4j # Generates a code coverage report in Crap4j format. See Code Coverage Analysis for more details. # Please note that this functionality is only available when the tokenizer and Xdebug extensions are installed. --coverage-html # Generates a code coverage report in HTML format. See Code Coverage Analysis for more details. # Please note that this functionality is only available when the tokenizer and Xdebug extensions are installed. --coverage-php # Generates a serialized PHP_CodeCoverage object with the code coverage information. # Please note that this functionality is only available when the tokenizer and Xdebug extensions are installed. --coverage-text # Generates a logfile or command-line output in human readable format with the code coverage information for the tests run. See Logging for more details. # Please note that this functionality is only available when the tokenizer and Xdebug extensions are installed. ``` -------------------------------- ### Running Tests from a Specific File Source: https://docs.phpunit.de/en/8.5/organizing-tests This command runs tests only from a single specified test case file. It's useful for isolating and testing specific sets of functionality. The `--bootstrap` option ensures necessary setup code is loaded. ```bash $ phpunit --bootstrap src/autoload.php tests/CurrencyTest.php ``` -------------------------------- ### PHPUnit assertXmlStringEqualsXmlFile Assertion Example Source: https://docs.phpunit.de/en/8.5/assertions Shows how to use the assertXmlStringEqualsXmlFile assertion in PHPUnit, which compares an XML string against the content of an XML file. The example demonstrates a test case designed to fail due to content mismatch. ```php assertXmlStringEqualsXmlFile( '/home/sb/expected.xml', ''); } } ``` -------------------------------- ### Assert String Starts With (PHP) Source: https://docs.phpunit.de/en/8.5/assertions Asserts that a string begins with a specified prefix. Reports an error if the string does not start with the prefix. The inverse assertion is assertStringStartsNotWith(). ```PHP assertStringStartsWith('prefix', 'foo'); } } ``` -------------------------------- ### Download and Version Check PHPUnit PHAR Source: https://docs.phpunit.de/en/8.5/installation This command sequence demonstrates how to download the PHPUnit 8.5 PHAR archive using `curl` and then check its version using the `php` command. ```bash $ curl -LO https://phar.phpunit.de/phpunit-8.5.phar $ php phpunit-8.5.phar --version ``` -------------------------------- ### PHPUnit Test with Array Data Provider Source: https://docs.phpunit.de/en/8.5/writing-tests-for-phpunit Demonstrates a PHPUnit test case that uses a data provider method returning an array of arrays. The `@dataProvider` annotation links the test method to the provider. The provider supplies arguments for the test method, which asserts the correctness of an addition operation. This example shows a basic setup for parameterized testing. ```php assertSame($expected, $a + $b); } public function additionProvider(): array { return [ [0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 3] ]; } } ``` -------------------------------- ### Add PHPUnit as a Dev Dependency with Composer Source: https://docs.phpunit.de/en/8.5/installation This snippet shows the Composer command to add PHPUnit as a development dependency to a project. Managing PHPUnit via Composer is the recommended approach for projects using Composer. ```bash composer require --dev phpunit/phpunit ^8.5 ``` -------------------------------- ### Programmatically Skip Test with markTestSkipped() in PHP Source: https://docs.phpunit.de/en/8.5/incomplete-and-skipped-tests This code demonstrates how to skip a PHPUnit test case programmatically. The `setUp()` method checks if the 'mysqli' extension is loaded. If not, `markTestSkipped()` is called to skip the test and provide an explanatory message. This method is useful for environment-dependent tests. ```php markTestSkipped( 'The MySQLi extension is not available.' ); } } public function testConnection(): void { // ... } } ``` -------------------------------- ### PHPUnit Test Case Template Methods Overview Source: https://docs.phpunit.de/en/8.5/fixtures Illustrates the usage of all available template methods within a PHPUnit test case class, including setUpBeforeClass(), setUp(), assertPreConditions(), testOne(), testTwo(), assertPostConditions(), tearDown(), tearDownAfterClass(), and onNotSuccessfulTest(). This helps visualize the test execution lifecycle and how each method is invoked. ```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 assertXmlFileEqualsXmlFile Assertion Example Source: https://docs.phpunit.de/en/8.5/assertions Illustrates the assertXmlFileEqualsXmlFile assertion in PHPUnit, used to compare the content of two XML files. The example provided shows a scenario where the files are not equal, leading to a failure. ```php assertXmlFileEqualsXmlFile( '/home/sb/expected.xml', '/home/sb/actual.xml'); } } ``` -------------------------------- ### Download PHPUnit PHAR and Signature Source: https://docs.phpunit.de/en/8.5/installation This snippet demonstrates how to download the PHPUnit PHAR archive and its detached PGP signature using the `curl` command. These files are necessary for verifying the integrity and authenticity of the release. ```bash $ curl -LO https://phar.phpunit.de/phpunit-8.5.phar $ curl -LO https://phar.phpunit.de/phpunit-8.5.phar.asc ``` -------------------------------- ### PHPUnit Test Using Multiple Data Providers Source: https://docs.phpunit.de/en/8.5/writing-tests-for-phpunit Illustrates how a single PHPUnit test method can utilize data from multiple data providers. The 'testAdd' method in 'DataTest' uses both 'additionWithNonNegativeNumbersProvider' and 'additionWithNegativeNumbersProvider' to test addition with various inputs. All data providers are executed before setUpBeforeClass() and setUp(). ```php assertSame($expected, $a + $b); } public function additionWithNonNegativeNumbersProvider(): array { return [ [0, 1, 1], [1, 0, 1], [1, 1, 3] ]; } public function additionWithNegativeNumbersProvider(): array { return [ [-1, 1, 0], [-1, -1, -2], [1, -1, 0] ]; } } ``` -------------------------------- ### Filtering Tests by Method Name Source: https://docs.phpunit.de/en/8.5/organizing-tests This command demonstrates how to run specific tests within a file by filtering them based on a method name. This allows for highly targeted test execution, which can be useful for debugging or verifying specific behaviors. The `--bootstrap` option is used for setup. ```bash $ phpunit --bootstrap src/autoload.php --filter testObjectCanBeConstructedForValidConstructorArgument tests ``` -------------------------------- ### Enabling PHAR Execution in php.ini with Suhosin Source: https://docs.phpunit.de/en/8.5/installation If the Suhosin extension is enabled, PHAR execution needs to be explicitly allowed in the `php.ini` file. This snippet shows the required configuration line. ```ini suhosin.executor.include.whitelist = phar ``` -------------------------------- ### Specify Method Coverage with @covers Annotation Source: https://docs.phpunit.de/en/8.5/code-coverage-analysis This example showcases using the @covers annotation on individual test methods to specify which methods of the BankAccount class are being tested. It includes tests for getBalance, withdrawMoney, and depositMoney, demonstrating assertions for initial balance, preventing negative balances, and successful deposits/withdrawals. ```php ba = new BankAccount; } /** * @covers \BankAccount::getBalance */ public function testBalanceIsInitiallyZero(): void { $this->assertSame(0, $this->ba->getBalance()); } /** * @covers \BankAccount::withdrawMoney */ public function testBalanceCannotBecomeNegative(): void { try { $this->ba->withdrawMoney(1); } catch (BankAccountException $e) { $this->assertSame(0, $this->ba->getBalance()); return; } $this->fail(); } /** * @covers \BankAccount::depositMoney */ public function testBalanceCannotBecomeNegative2(): void { try { $this->ba->depositMoney(-1); } catch (BankAccountException $e) { $this->assertSame(0, $this->ba->getBalance()); return; } $this->fail(); } /** * @covers \BankAccount::getBalance * @covers \BankAccount::depositMoney * @covers \BankAccount::withdrawMoney */ public function testDepositWithdrawMoney(): void { $this->assertSame(0, $this->ba->getBalance()); $this->ba->depositMoney(1); $this->assertSame(1, $this->ba->getBalance()); $this->ba->withdrawMoney(1); $this->assertSame(0, $this->ba->getBalance()); } } ``` -------------------------------- ### Generate TestDox Console Output (PHP) Source: https://docs.phpunit.de/en/8.5/textui This command executes tests for the BankAccountTest class and generates TestDox output directly to the console. It requires PHPUnit to be installed and the test file to be present. ```shell $ phpunit --testdox BankAccountTest ``` -------------------------------- ### Define Pre-Class Setup Methods with @beforeClass (PHP) Source: https://docs.phpunit.de/en/8.5/annotations The `@beforeClass` annotation in PHPUnit designates static methods to be executed once before any test methods in a test class run. This annotation is ideal for setting up shared resources or complex initial states that are common across all tests in the class. ```php addEntry("suzy", "Hello world!"); $queryTable = $this->getConnection()->createQueryTable( 'guestbook', 'SELECT * FROM guestbook' ); $expectedTable = $this->createFlatXmlDataSet("expectedBook.xml") ->getTable("guestbook"); $this->assertTablesEqual($expectedTable, $queryTable); } } ``` -------------------------------- ### Advanced Stubbing using Mock Builder in PHPUnit (PHP) Source: https://docs.phpunit.de/en/8.5/test-doubles Shows how to use PHPUnit's Mock Builder API to create a stub for 'SomeClass' with specific configurations like disabling constructors and argument cloning. It then configures the 'doSomething' method to return 'foo', similar to the basic stubbing example, but with more control over the stub's creation. ```php getMockBuilder(SomeClass::class) ->disableOriginalConstructor() ->disableOriginalClone() ->disableArgumentCloning() ->disallowMockingUnknownTypes() ->getMock(); // Configure the stub. $stub->method('doSomething') ->willReturn('foo'); // Calling $stub->doSomething() will now return // 'foo'. $this->assertSame('foo', $stub->doSomething()); } } ``` -------------------------------- ### PHPUnit Test Dependency Failure Handling Source: https://docs.phpunit.de/en/8.5/writing-tests-for-phpunit This example illustrates how PHPUnit handles test failures when dependencies are involved. `testOne` is designed to fail. `testTwo` depends on `testOne`. When `testOne` fails, `testTwo` is automatically skipped, demonstrating PHPUnit's mechanism for defect localization by exploiting test dependencies. ```php assertTrue(false); } /** * @depends testOne */ public function testTwo(): void { } } ``` -------------------------------- ### PHPUnit Filtering Tests with Regular Expressions Source: https://docs.phpunit.de/en/8.5/textui The `--filter` option allows running tests that match a given regular expression pattern. This section provides examples of how to filter tests based on namespace, class, method, and data provider names. ```bash --filter # Only runs tests whose name matches the given regular expression pattern. If the pattern is not enclosed in delimiters, PHPUnit will enclose the pattern in `/` delimiters. # The test names to match will be in one of the following formats: # TestNamespace\TestCaseClass::testMethod # The default test name format is the equivalent of using the __METHOD__ magic constant inside the test method. # TestNamespace\TestCaseClass::testMethod with data set #0 # When a test has a data provider, each iteration of the data gets the current index appended to the end of the default test name. # TestNamespace\TestCaseClass::testMethod with data set "my named data" # When a test has a data provider that uses named sets, each iteration of the data gets the current name appended to the end of the default test name. See Example 3.1 for an example of named data sets. # Example 3.1 Named data sets # ```php # namespace TestNamespace; # # use PHPUnit\Framework\TestCase; # # class TestCaseClass extends TestCase # { # /** # * @dataProvider provider # */ # public function testMethod($data) # { # $this->assertTrue($data); # } # # public function provider() # { # return [ # 'my named data' => [true], # 'my data' => [true] # ]; # } # } # # ``` # # /path/to/my/test.phpt # The test name for a PHPT test is the filesystem path. # See Example 3.2 for examples of valid filter patterns. # Example 3.2 Filter pattern examples # ``` # --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)$/' # # ``` # # See Example 3.3 for some additional shortcuts that are available for matching data providers. # Example 3.3 Filter shortcuts # ``` # --filter 'testMethod#2' # --filter 'testMethod#2-4' # --filter '#2' ``` -------------------------------- ### Verify PHPUnit PHAR Signature with GPG Source: https://docs.phpunit.de/en/8.5/installation This snippet shows the initial verification of a PHPUnit PHAR's detached PGP signature using the `gpg --verify` command. It highlights potential issues like missing public keys, which prevent full signature validation. ```bash $ gpg --verify phpunit-8.5.phar.asc gpg: assuming signed data in 'phpunit-8.5.phar' gpg: Signature made Mon Jul 19 06:13:42 2021 UTC gpg: using RSA key D8406D0D82947747293778314AA394086372C20A gpg: issuer "sb@sebastian-bergmann.de" gpg: Can't check signature: No public key ``` -------------------------------- ### Re-verify PHPUnit PHAR Signature after Key Import Source: https://docs.phpunit.de/en/8.5/installation After importing the release manager's public key, this snippet shows how to re-verify the PHPUnit PHAR signature. It demonstrates a 'Good signature' result but also warns about the key not being trusted, emphasizing the need for external key validation. ```bash $ gpg --verify phpunit-8.5.phar.asc gpg: assuming signed data in 'phpunit-8.5.phar' gpg: Signature made Mon Jul 19 06:13:42 2021 UTC gpg: using RSA key D8406D0D82947747293778314AA394086372C20A gpg: issuer "sb@sebastian-bergmann.de" gpg: Good signature from "Sebastian Bergmann " [unknown] gpg: aka "Sebastian Bergmann " [unknown] gpg: aka "Sebastian Bergmann " [unknown] gpg: aka "Sebastian Bergmann " [unknown] gpg: aka "Sebastian Bergmann " [unknown] gpg: aka "[jpeg image of size 40635]" [unknown] gpg: WARNING: This key is not certified with a trusted signature! gpg: There is no indication that the signature belongs to the owner. Primary key fingerprint: D840 6D0D 8294 7747 2937 7831 4AA3 9408 6372 C20A ``` -------------------------------- ### PHPUnit XML Test Results Log Example Source: https://docs.phpunit.de/en/8.5/logging This XML snippet demonstrates the structure of a test results logfile generated by PHPUnit, adhering to the JUnit Ant task format. It includes details about test suites and individual test cases, their status, assertions, and execution time. This format is useful for integrating with CI/CD tools and reporting systems. ```xml ``` -------------------------------- ### Skip Tests Using @requires Annotation in PHP Source: https://docs.phpunit.de/en/8.5/incomplete-and-skipped-tests This example shows how to use the `@requires` annotation in PHPUnit to specify preconditions for tests. The `DatabaseTest` class requires the 'mysqli' extension, and the `testConnection` method further requires PHP version 5.3 or higher. This declarative approach helps manage test dependencies and ensures tests only run when their requirements are met. ```php = 5.3 */ public function testConnection(): void { // Test requires the mysqli extension and PHP >= 5.3 } // ... All other tests require the mysqli extension } ``` -------------------------------- ### PHPUnit XML Log with Failures and Errors Example Source: https://docs.phpunit.de/en/8.5/logging This XML snippet illustrates how PHPUnit logs test failures and errors in its test results file. It showcases the structure for denoting failures and errors within individual test cases, including the type of failure/error and associated messages. This detailed logging is crucial for debugging and understanding test execution outcomes. ```xml testFailure(FailureErrorTest) Failed asserting that <integer:2> matches expected value <integer:1>. /home/sb/FailureErrorTest.php:8 testError(FailureErrorTest) Exception: /home/sb/FailureErrorTest.php:13 ``` -------------------------------- ### Running Tests with PHPUnit Command-Line Runner Source: https://docs.phpunit.de/en/8.5/textui Demonstrates how to execute tests using the PHPUnit command-line interface. It shows the basic command structure and the expected output for a successful test run. ```bash $ phpunit ArrayTest PHPUnit 8.5.0 by Sebastian Bergmann and contributors. .. Time: 0 seconds OK (2 tests, 2 assertions) ``` -------------------------------- ### PHPUnit assertArrayHasKey() Assertion Example Source: https://docs.phpunit.de/en/8.5/assertions Example of using the `assertArrayHasKey()` method in PHPUnit. This assertion verifies if a given array has a specific key. The example demonstrates a failing test case where the key is not present in the array, along with the expected output from the PHPUnit runner. ```PHP assertArrayHasKey('foo', ['bar' => 'baz']); } } ``` -------------------------------- ### PHPUnit Command-Line Help Source: https://docs.phpunit.de/en/8.5/textui Displays the help message for the PHPUnit command-line test runner, listing available options and usage instructions. This is the primary entry point for understanding how to interact with PHPUnit via the terminal. ```bash phpunit --help ``` -------------------------------- ### PHP Implementation of Test Listener Registration Source: https://docs.phpunit.de/en/8.5/configuration PHP code demonstrating the instantiation of a custom listener with arguments matching the XML configuration. ```php $listener = new MyListener( ['Sebastian'], 22, 'April', 19.78, null, new stdClass ); ``` -------------------------------- ### PHPUnit Miscellaneous Options Source: https://docs.phpunit.de/en/8.5/textui General purpose command-line options for PHPUnit, including help, version checking, and printing usage information. ```bash -h|--help Prints this usage information --version Prints the version and exits --atleast-version Checks that version is greater than min and exits --check-version Check whether PHPUnit is the latest version ``` -------------------------------- ### PHPUnit assertTrue Assertion Example Source: https://docs.phpunit.de/en/8.5/assertions Demonstrates the usage of PHPUnit's assertTrue assertion, which reports an error if a given condition is false. This example shows a test case that is expected to fail. ```php assertTrue(false); } } ``` -------------------------------- ### PHPUnit assertXmlStringEqualsXmlString Assertion Example Source: https://docs.phpunit.de/en/8.5/assertions Demonstrates the assertXmlStringEqualsXmlString assertion in PHPUnit for comparing two XML strings. The example illustrates a test case where the expected and actual XML strings differ, resulting in a failure. ```php assertXmlStringEqualsXmlString( '', ''); } } ``` -------------------------------- ### Configure Test Runner Extension with Arguments Source: https://docs.phpunit.de/en/8.5/configuration Configures a test runner extension by passing various data types as constructor arguments in order. ```xml 1 2 3 hello world true 1.23 value1 value2 constructor arg 1 constructor arg 2 ``` -------------------------------- ### Running PHPUnit Tests Source: https://docs.phpunit.de/en/8.5/textui Commands for executing tests. This includes running tests from a specific class or a specified file, and how to run tests from a class that inherits from PHPUnit\Framework\TestCase or provides a static suite method. ```bash phpunit UnitTest # Runs the tests that are provided by the class UnitTest. This class is expected to be declared in the UnitTest.php sourcefile. # UnitTest must be either a class that inherits from PHPUnit\Framework\TestCase or a class that provides a public static suite() method which returns a PHPUnit\Framework\Test object, for example an instance of the PHPUnit\Framework\TestSuite class. phpunit UnitTest UnitTest.php # Runs the tests that are provided by the class UnitTest. This class is expected to be declared in the specified sourcefile. ``` -------------------------------- ### Setting $_GET Super-global with Source: https://docs.phpunit.de/en/8.5/configuration Configures values for the `$_GET` super-global array within the PHPUnit XML configuration. The 'name' attribute specifies the key, and the 'value' attribute sets the corresponding value. This is useful for simulating GET requests. ```xml ``` ```php $_GET['foo'] = 'bar'; ``` -------------------------------- ### PHPUnit Configuration Options Source: https://docs.phpunit.de/en/8.5/textui Options to control PHPUnit's configuration loading and generation. This includes specifying configuration files, ignoring default configurations, and generating a new configuration file with suggested settings. ```bash --prepend A PHP script that is included as early as possible --bootstrap A PHP script that is included before the tests run -c|--configuration Read configuration from XML file --no-configuration Ignore default configuration file (phpunit.xml) --no-logging Ignore logging configuration --no-extensions Do not load PHP extensions --include-path Prepend PHP's include_path with given path(s) -d key[=value] Sets a php.ini value --generate-configuration Generate configuration file with suggested settings --cache-result-file= Specify result cache path and filename ``` -------------------------------- ### PHPUnit Test Execution Output Source: https://docs.phpunit.de/en/8.5/writing-tests-for-phpunit This is a sample output from running a PHPUnit test suite. It indicates the version of PHPUnit used, shows the progress of tests (a single dot representing a passing test), and provides a summary of execution time, memory usage, and the number of tests run and assertions made. ```text $ phpunit ErrorSuppressionTest PHPUnit 8.5.0 by Sebastian Bergmann and contributors. . Time: 1 seconds, Memory: 5.25Mb OK (1 test, 1 assertion) ``` -------------------------------- ### Configure Test Suites with Directories Source: https://docs.phpunit.de/en/8.5/configuration Defines test suites by specifying directories to search for tests. Each test suite requires a 'name' attribute. ```xml tests/unit tests/integration tests/edge-to-edge ``` -------------------------------- ### Running All Tests from a Directory Source: https://docs.phpunit.de/en/8.5/organizing-tests This command executes all tests found within the specified 'tests' directory. PHPUnit will recursively search for files ending in 'Test.php' and run the tests within them. The `--bootstrap` option specifies a file to load before running tests. ```bash $ phpunit --bootstrap src/autoload.php tests ``` -------------------------------- ### Use Xdebug Filter Script for Code Coverage with PHPUnit Source: https://docs.phpunit.de/en/8.5/code-coverage-analysis This command utilizes the generated Xdebug filter script with PHPUnit to create an HTML code coverage report. The `--prepend` option ensures the filter script is loaded early, optimizing the process. It requires the PHPUnit executable, the path to the filter script, and an output directory for the report. ```bash $ phpunit --prepend build/xdebug-filter.php --coverage-html build/coverage-report ``` -------------------------------- ### Get Mock Builder - PHPUnit Source: https://docs.phpunit.de/en/8.5/test-doubles Provides a fluent interface to customize the generation of a test double object for a specified type. This allows for more control over constructor arguments, method mocking, and other aspects compared to `createStub` and `createMock`. ```php getMockBuilder(MyService::class) ->setConstructorArgs([$arg1, $arg2]) // Optional: specify constructor arguments ->onlyMethods(['method1', 'method2']) // Optional: mock only specific methods ->disableOriginalConstructor() // Optional: disable original constructor ->getMock(); // Configure the mock's behavior as needed // $mockBuilder->method('method1')->willReturn('value1'); // Use the configured mock object // $this->assertEquals('value1', $mockBuilder->method1()); } } ``` -------------------------------- ### PHPUnit: Test Identical Object Passed to Mocked Method Source: https://docs.phpunit.de/en/8.5/test-doubles This example demonstrates how to verify that a mocked method is called exactly once with the exact same object instance that was passed into the test. It uses the `identicalTo()` constraint for precise object comparison. ```php getMockBuilder(stdClass::class) ->setMethods(['foo']) ->getMock(); $mock->expects($this->once()) ->method('foo') ->with($this->identicalTo($expectedObject)); $mock->foo($expectedObject); } } ``` -------------------------------- ### Run Test Suite by Name using CLI - PHPUnit Source: https://docs.phpunit.de/en/8.5/organizing-tests This command executes a specific test suite named 'money' using the PHPUnit command-line interface. It requires the bootstrap file to be specified for loading the test environment and dependencies. ```bash $ phpunit --bootstrap src/autoload.php --testsuite money ``` -------------------------------- ### PHPUnit Test Execution Output for Weak Comparison Source: https://docs.phpunit.de/en/8.5/writing-tests-for-phpunit This output shows the result of running the PHPUnit test case that demonstrates an edge case in diff generation. It illustrates the diff highlighting differences in index 0 ('1' vs 1) and index 2 (33 vs 3), even though assertEquals() treats them as equal. ```bash $ phpunit ArrayWeakComparisonTest PHPUnit 8.5.0 by Sebastian Bergmann and contributors. F Time: 0 seconds, Memory: 5.25Mb There was 1 failure: 1) ArrayWeakComparisonTest::testEquality Failed asserting that two arrays are equal. --- +++ Actual @@ @@ Array ( - 0 => 1 + 0 => '1' 1 => 2 - 2 => 3 + 2 => 33 3 => 4 4 => 5 5 => 6 ) /home/sb/ArrayWeakComparisonTest.php:7 FAILURES! Tests: 1, Assertions: 1, Failures: 1. ``` -------------------------------- ### Stubbing a Method Call in PHPUnit (PHP) Source: https://docs.phpunit.de/en/8.5/test-doubles Demonstrates how to create a stub for 'SomeClass' and configure its 'doSomething' method to return a fixed string value 'foo'. This is a fundamental example of using PHPUnit's stubbing capabilities to control the behavior of dependencies during testing. ```php createStub(SomeClass::class); // Configure the stub. $stub->method('doSomething') ->willReturn('foo'); // Calling $stub->doSomething() will now return // 'foo'. $this->assertSame('foo', $stub->doSomething()); } } ``` -------------------------------- ### PHPUnit Logging and Documentation Generation Source: https://docs.phpunit.de/en/8.5/textui Options for generating log files and documentation from test runs. This includes JUnit XML format for test results and TestDox for agile documentation in HTML or text. ```bash --log-junit # Generates a logfile in JUnit XML format for the tests run. See Logging for more details. --testdox-html and --testdox-text # Generates agile documentation in HTML or plain text format for the tests that are run (see TestDox). ``` -------------------------------- ### Testing Method Calls with Prophecy in PHPUnit Source: https://docs.phpunit.de/en/8.5/test-doubles This example demonstrates how to use Prophecy within PHPUnit to test if a method is called exactly once with specific arguments. It involves creating a prophecy for a class, setting expectations on its methods, and then revealing the prophecy to obtain a mock object. ```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(); } } ``` -------------------------------- ### Configure Code Coverage Whitelist Source: https://docs.phpunit.de/en/8.5/configuration Sets up the whitelist for code coverage reporting using the '' element. Allows specifying directories and excluding specific files. ```xml src src/autoload.php ``` -------------------------------- ### PHPUnit Test with Named Datasets Source: https://docs.phpunit.de/en/8.5/writing-tests-for-phpunit Illustrates using a data provider in PHPUnit where each dataset is assigned a string key. This approach enhances test readability and debuggability by providing meaningful names in the test output, especially when a test fails. The structure is similar to the array data provider but includes descriptive keys for each data set. ```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] ]; } } ``` -------------------------------- ### PHPUnit Logging Options Source: https://docs.phpunit.de/en/8.5/textui Options for logging test execution results in different formats. This includes JUnit XML for CI servers, TeamCity format, and TestDox formats (HTML, Text, XML) for more readable documentation of test outcomes. ```bash phpunit --log-junit phpunit --log-teamcity phpunit --testdox-html phpunit --testdox-text phpunit --testdox-xml phpunit --reverse-list ``` -------------------------------- ### PHPUnit: Test Method Called Twice with Specific Arguments Source: https://docs.phpunit.de/en/8.5/test-doubles This example demonstrates how to test if a mocked method is called exactly twice with specific, different arguments using `withConsecutive`. It utilizes `getMockBuilder`, `setMethods`, `expects`, `exactly`, `method`, `withConsecutive`, and argument matchers like `equalTo` and `greaterThan`. ```php getMockBuilder(stdClass::class) ->setMethods(['set']) ->getMock(); $mock->expects($this->exactly(2)) ->method('set') ->withConsecutive( [$this->equalTo('foo'), $this->greaterThan(0)], [$this->equalTo('bar'), $this->greaterThan(0)] ); $mock->set('foo', 21); $mock->set('bar', 48); } } ``` -------------------------------- ### Class with Return Type Declaration for Stubbing (PHP) Source: https://docs.phpunit.de/en/8.5/test-doubles Illustrates a PHP class 'C' with a method 'm' that has a return type declaration specifying an object of type 'D'. This example is relevant to PHPUnit's automatic stubbing behavior, where return types influence default stubbed values. ```php ``` -------------------------------- ### PHPUnit Code Coverage Reporting Options Source: https://docs.phpunit.de/en/8.5/textui Options for generating code coverage reports in various formats like Clover XML, Crap4J XML, HTML, PHP, text, and PHPUnit XML. It also includes options for whitelisting directories for coverage analysis and disabling coverage-related features. ```bash phpunit --coverage-clover phpunit --coverage-crap4j phpunit --coverage-html phpunit --coverage-php phpunit --coverage-text= phpunit --coverage-xml phpunit --whitelist phpunit --disable-coverage-ignore phpunit --no-coverage phpunit --dump-xdebug-filter ``` -------------------------------- ### Share Database Fixture Across PHPUnit Tests Source: https://docs.phpunit.de/en/8.5/fixtures This snippet demonstrates how to share a database connection fixture across all tests within a PHPUnit test class. It uses setUpBeforeClass() to establish the connection once before any tests run and tearDownAfterClass() to close the connection after all tests have completed. This is useful for performance, but should be used cautiously. ```php assertFalse(@$writer->write('/is-not-writeable/file', 'stuff')); } } final class FileWriter { public function write($file, $content) { $file = fopen($file, 'w'); if ($file === false) { return false; } // ... } } ``` -------------------------------- ### PHPUnit Command-Line Output for Incomplete Tests Source: https://docs.phpunit.de/en/8.5/incomplete-and-skipped-tests Illustrates the output produced by the PHPUnit command-line test runner when incomplete tests are present. An incomplete test is indicated by 'I' in the verbose output. ```bash $ phpunit --verbose SampleTest PHPUnit 8.5.0 by Sebastian Bergmann and contributors. I Time: 0 seconds, Memory: 3.95Mb There was 1 incomplete test: 1) SampleTest::testSomething This test has not been implemented yet. /home/sb/SampleTest.php:12 OK, but incomplete or skipped tests! Tests: 1, Assertions: 1, Incomplete: 1. ```