Stub example in PHP
user_4333156
php
a year ago
1.1 kB
9
Indexable
<?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);
}
}
Editor is loading...
Leave a Comment