Installing PHPUnit with Composer


Installing PHPUnit with Composer

Anna
Now that the project is ready for it, let’s add unit tests. If you haven’t created a tests directory or a PHPUnit configuration file yet, that’s okay—we’ll set them up now. First, we need PHPUnit as a development dependency, because we run tests during development and don’t need the testing framework on the production server.

Maria
The package being installed here is PHPUnit, version 10.2.3. We can add it with Composer using `composer require --dev phpunit/phpunit`. If Composer asks whether to install it as a development dependency, we say yes. The `--dev` option does the same thing directly, placing PHPUnit under `require-dev` in `composer.json`.

Anna
Once Composer finishes, we can check `composer.json` to confirm PHPUnit appears under `require-dev`. Next, we configure `phpunit.xml.dist`, the distributed PHPUnit configuration file. The PHPUnit 10 documentation lists many available options, so it’s useful to consult it when you need more than this basic setup.

Maria
For this project, the configuration points PHPUnit to Composer’s `vendor/autoload.php` file as its bootstrap. That gives tests the same Composer autoloading support the application uses, so classes can be loaded automatically. We don’t need a separate test bootstrap file when the Composer autoloader is all we need.

Anna
We can also enable colored test output, which makes results easier to scan. The configuration includes a cache directory, commonly `.phpunit.cache`, and a test suite named `unit` that looks for tests in the `tests` directory. It can also identify the project’s source files in `src`, using the PHP file suffix, so the source is included for coverage-related configuration.

Maria
The file may include a schema or version declaration used by PHPUnit 10. If an older configuration is out of date, PHPUnit can suggest a migration; you can use the compatible version it generates or follow the current documentation. Formatting and indentation are just presentation—the important part is that the XML structure and paths are correct.

Anna
Let’s distinguish two kinds of files that are easy to confuse. A `.gitattributes` file can use `export-ignore` to keep development-only files out of source archives—for example, tests, PHPUnit configuration, or GitHub-specific files when packaging a library. That matters when someone downloads the package archive and doesn’t need your development tools or tests.

Maria
By contrast, `.gitignore` controls which untracked files Git ignores in your working repository. It’s appropriate for generated PHPUnit cache files and a local `phpunit.xml` override. Keep `phpunit.xml.dist` as the shared template, though, and don’t ignore the tests themselves if you want them version-controlled. A local `phpunit.xml` can override the distributed file, so it’s often left uncommitted.

Anna
With the configuration in place, we can create the `tests` directory if it doesn’t already exist. Inside it, we’ll add a test for the user entity, named `UserTest.php`. PHPUnit expects the test class name to end in `Test`, which is why we use `UserTest` rather than simply `User`.

Maria
The test class is marked `final`, a common choice for PHPUnit test classes because they generally aren’t intended to be extended. We also declare `strict_types=1`. That tells PHP to enforce the declared types strictly rather than silently coercing values in situations where it would otherwise do so.

Anna
Our class extends PHPUnit’s `TestCase`, which provides the assertion methods and test lifecycle support. The namespace should follow the project’s namespace convention, with a test namespace that corresponds to the project and the entity area. We also import the `User` entity so the tests can construct it.

Maria
We’ll keep a `User` object on the test class and initialize it in a protected `setUp` method. PHPUnit calls `setUp` before each test, much like a constructor for test preparation. Call `parent::setUp()` as well, then create a fresh `User` instance so each test starts with a clean object.

Anna
The first test checks the sequential ID getter. We set the entity’s sequential ID to a known value, such as 55, then use `assertSame` to compare that expected value with the result of `getSequentialId()`. `assertSame` is a strict comparison—it checks both value and type, much like PHP’s `===` operator.

Maria
That distinction is useful. If the expected value is the integer 55 but the getter returns the string `"55"`, a loose equality check might consider them equivalent, while `assertSame` will fail. A passing test confirms that the entity returns exactly the value and type we expect.

Anna
The next test can check the user’s UUID. We create one with the Ramsey UUID library, using a UUID version 4 generator, and convert it to a string with `toString()`. That conversion matters because the library returns a UUID object, while this entity field is expected to hold a string.

Maria
Then we set that string on the user entity and use `assertSame` to compare it with `getUserUuid()`. The two basic tests cover the sequential ID and UUID getters. When we first run PHPUnit, a passing test may not produce a detailed failure message; deliberately changing an expected value is a quick way to verify that the test really runs and fails when it should.

Anna
We can run the whole suite with the `phpunit` command if PHPUnit is available globally. If it isn’t, run the project’s executable at `vendor/bin/phpunit`. You can also ask for the version with the lowercase `--version` or `-V` option.

Maria
Let’s add a more complete test for `User::unserialize()`. We’ll pass it an associative array containing the fields the entity supports: an ID, a UUID string, first and last names, email, phone, password, and creation date. Then we’ll verify that unserializing the data leaves each getter returning the corresponding value.

Anna
For example, the test data might contain a first name like Pierre, a last name like Surya, an example email address, and a dummy phone number and password. The creation date should use the same format the project stores in its users table. We can copy a representative date from the database or query that field, so the test uses a value consistent with the application.

Maria
For every supported field, we compare the expected array value with the matching getter using `assertSame`: the ID with the sequential ID getter, the UUID with the UUID getter, and likewise for first name, last name, email, phone, password, and creation date. That gives us a focused check that `unserialize()` populates the entity correctly.

Anna
The test run should now report three tests: the sequential ID test, the UUID test, and the unserialize test. If we change one expected value—for instance, expecting Henry when the input contains Pierre—the assertion should fail and show the mismatch. After restoring the correct value, the suite should pass again.

Maria
You can run just one test with PHPUnit’s filter option. Give it the test class and method name, such as a filter matching `UserTest::testOnSerialize`. That’s handy while you’re working on one behavior, while running the full suite is useful for checking that changes haven’t broken other tests.

Anna
There may be additional columns in the database, such as a session token or the time of the last session. But if the user entity doesn’t retrieve or expose those fields yet, there’s no getter behavior to test for them at this stage. Our tests should cover what the entity currently implements, not functionality that hasn’t been added.

Maria
Before committing, run the tests again and check the files Git sees. Add the PHPUnit configuration, test class, and `.gitattributes` as appropriate. Make sure the generated PHPUnit cache stays ignored, along with any local `phpunit.xml` override; keep the distributed `phpunit.xml.dist` and the test code in version control.

Anna
Finally, commit the work with a message such as `Add PHPUnit tests`, then push it. We’ve installed the testing framework only for development, configured how it discovers and loads the project, and written checks for the user entity’s IDs and unserialization behavior. That gives us a solid starting point for adding more tests as the entity and project grow.

Ask anything
We've read this whole study set, so questions about it get the best answers.