要测试 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 依赖注入的有效性,并确保类能够正确地接收和使用其依赖项。