要測試 PHP 依賴注入的有效性,可以按照以下步驟進行:
class Database {
public function connect() {
// Connect to database
}
}
class UserService {
private $db;
public function __construct(Database $db) {
$this->db = $db;
}
public function getUsers() {
return $this->db->query('SELECT * FROM users');
}
}
class DependencyInjectionTest extends PHPUnit_Framework_TestCase {
public function testDependencyInjection() {
$db = $this->getMock('Database');
$db->expects($this->once())
->method('query')
->will($this->returnValue(['user1', 'user2']));
$userService = new UserService($db);
$users = $userService->getUsers();
$this->assertEquals(['user1', 'user2'], $users);
}
}
通過這些步驟,您可以測試 PHP 依賴注入的有效性,并確保類能夠正確地接收和使用其依賴項。