Stub example in PHP

 avatar
user_4333156
php
12 days ago
1.1 kB
3
Indexable
Never
<?php

use PHPUnit\Framework\TestCase;

class UserRepository {
    private $db;

    public function __construct(Database $db) {
        $this->db = $db;
    }

    public function getUserById($id) {
        return $this->db->findUserById($id);
    }
}

class Database {
    public function findUserById($id) {
        // Normally this would interact with the database
        return null;
    }
}

class UserRepositoryTest extends TestCase {

    public function testGetUserByIdReturnsCorrectUser() {
        // Create a stub for the Database class
        $dbStub = $this->createStub(Database::class);

        // Configure the stub to return a specific value for findUserById
        $dbStub->method('findUserById')
               ->willReturn(['id' => 1, 'name' => 'John Doe']);

        // Inject the stub into the UserRepository
        $userRepository = new UserRepository($dbStub);

        // Test the getUserById method
        $result = $userRepository->getUserById(1);

        // Assert the result
        $this->assertEquals(['id' => 1, 'name' => 'John Doe'], $result);
    }
}
Leave a Comment