Unit test means: pick one small PHP method and test only that method. No browser. No HTTP. No real app flow. This is the easiest place to start.
Summary: Test one PHP method directly.
Here is our PHP function, which we want to test:
// File: src/LearningService.php
namespace SmallLearning;
final class LearningService
{
public function __construct(private LessonRepository $lessons)
{
}
public function lessonDetails(string $lessonId): array
{
$lesson = $this->lessons->find($lessonId);
if ($lesson === null) {
throw new \InvalidArgumentException('Unknown lesson id.');
}
return $lesson;
}
}Now we can create a test like this:
use SmallLearning\LearningService;
use SmallLearning\LessonRepository;
// Step 1: create the dependency first.
$lessons = new LessonRepository();
// Step 2: give that dependency to the service.
$service = new LearningService($lessons);
// Step 3: call the method we want to test.
$lesson = $service->lessonDetails('php-basics');
// Step 4: check the result.
$this->assertSame('Unit Test', $lesson['title']);Why this test works
- The class we are testing is LearningService in src/LearningService.php.
- At the top of that file you will see namespace SmallLearning;.
- That namespace name is why the test imports the class with use SmallLearning\LearningService;.
- Before writing the test, open the class and look at the constructor first.
- LearningService needs one LessonRepository object, so we create that object first.
- For beginners, this is easier to read in two lines, not in one nested line.
- Put this file in tests/unit/LearningServiceTest.php because it is a unit test.
- The test knows the class because tests/Support/TestAppFactory.php loads src/bootstrap.php, and bootstrap.php autoloads classes in the SmallLearning namespace.
- Inside the test file, use SmallLearning\LearningService; imports the class name you want to test.
- Simple rule: create object, call method, assert result.
- When you see assertSame(), remember the Basics lesson: exact expected value on the left, actual result on the right.
Real-life examples
- Example: on an ecommerce website, test a PriceCalculator class to check that a 20 percent discount on 100 becomes 80.
- Example: on a forum website, test a SlugService class to check that "Hello World" becomes "hello-world".
Remember this
- Open src/LearningService.php first
- Read the constructor first
- Create dependency in its own line
- Put file in tests/unit
- Import the class with use
- Run with php tests/run.php unit