Your First Test

Your First Test

Now that PHPUnit is installed, it’s time to write your first test.

Let’s walk through the basics of creating a test class, writing an assertion, and running it.

Step 1: Create a tests/ directory

This is where all your test files will live.

Create the folder:

mkdir tests

Step 2: Create your first test file

Inside the tests/ folder, create a file called ExampleTest.php:

What’s happening here:

  • Your class extends PHPUnit\Framework\TestCase, which gives you access to all PHPUnit features.
  • Each test method must start with test.
  • Inside the method, you make one or more assertions. In this case, assertTrue(true) is always going to pass.

Step 3: Run the test

To run your test, use the following command from the root of your project:

./vendor/bin/phpunit tests

Let’s break that down:

  • ./vendor/bin/phpunit is the test runner executable that was installed with Composer.
  • tests is the directory where we’ve placed our test file — it tells PHPUnit where to look for test classes.

You should see output like this:

PHPUnit 12.x.x by Sebastian Bergmann and contributors.

.                                                                   1 / 1 (100%)

Time: 00:00.012, Memory: 6.00 MB

OK (1 test, 1 assertion)

The single . means your test passed.

Step 4: Try a failing test

Let’s see what happens when a test fails. Change your assertion:

$this->assertTrue(false);

Then run the test again. You’ll see a failure message explaining what went wrong.

Test naming conventions

PHPUnit will look for test classes in the directory you specify when running the test command. By convention, most projects:

  • Place test files in a folder named tests/
  • Name files with the suffix Test.php
  • Ensure test classes extend PHPUnit\Framework\TestCase

Following these conventions helps keep your tests easy to discover and manage — especially once we introduce configuration later on.

Coming up next: we’ll look at how to organize tests into logical groups and folders as your project grows.

Complete and Continue  
Discussion

0 comments