Mock example in PHP
user_4333156
php
a year ago
1.2 kB
10
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) {
return null;
}
}
class UserRepositoryTest extends TestCase {
public function testGetUserByIdCallsFindUserByIdOnce() {
// Create a mock for the Database class
$dbMock = $this->createMock(Database::class);
// Set up the mock to expect findUserById to be called with 1 as parameter
$dbMock->expects($this->once())
->method('findUserById')
->with($this->equalTo(1))
->willReturn(['id' => 1, 'name' => 'John Doe']);
// Inject the mock into the UserRepository
$userRepository = new UserRepository($dbMock);
// Call the method
$result = $userRepository->getUserById(1);
// Assert the result
$this->assertEquals(['id' => 1, 'name' => 'John Doe'], $result);
}
}
Editor is loading...
Leave a Comment