本文目录导读:

在 PHP 中重置数据库测试数据有多种方法,以下是几种常用的方案:
使用迁移和种子数据(推荐)
// 使用 Laravel 的 Artisan 命令 // 刷新迁移并重新填充数据 php artisan migrate:fresh --seed // 或者只重置特定表 php artisan db:seed --class=YourTableSeeder // 回滚所有迁移并重新执行 php artisan migrate:refresh --seed
使用 SQL 脚本重置
// 创建重置脚本文件 reset_database.php
<?php
class DatabaseResetter {
private $pdo;
public function __construct($host, $dbname, $user, $pass) {
try {
$this->pdo = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("连接失败: " . $e->getMessage());
}
}
// 方法1: 执行 SQL 文件
public function resetWithSqlFile($filePath) {
try {
// 读取并执行 SQL 文件
$sql = file_get_contents($filePath);
$this->pdo->exec($sql);
echo "数据库重置成功!\n";
} catch (PDOException $e) {
echo "重置失败: " . $e->getMessage() . "\n";
}
}
// 方法2: 清空所有表
public function cleanAllTables() {
try {
$this->pdo->exec("SET FOREIGN_KEY_CHECKS = 0;");
$stmt = $this->pdo->query("SHOW TABLES");
while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
$table = $row[0];
// 清空表数据并重置自增ID
$this->pdo->exec("TRUNCATE TABLE `$table`");
echo "已清空表: $table\n";
}
$this->pdo->exec("SET FOREIGN_KEY_CHECKS = 1;");
echo "所有表已清空\n";
} catch (PDOException $e) {
echo "清空失败: " . $e->getMessage() . "\n";
}
}
// 方法3: 使用事务回滚测试数据
public function resetWithTransaction() {
$this->pdo->beginTransaction();
try {
// 在这里执行你的测试操作
// ... 测试代码
// 回滚事务,撤销所有更改
$this->pdo->rollBack();
echo "测试修改已回滚\n";
} catch (Exception $e) {
$this->pdo->rollBack();
echo "错误: " . $e->getMessage() . "\n";
}
}
// 方法4: 导出并重新导入数据库
public function restoreFromBackup($backupFile) {
try {
// 使用系统命令导入备份
$command = "mysql -u username -p password database_name < " . $backupFile;
exec($command, $output, $return_var);
if ($return_var === 0) {
echo "数据库从备份恢复成功\n";
} else {
echo "数据库恢复失败\n";
}
} catch (Exception $e) {
echo "恢复出错: " . $e->getMessage() . "\n";
}
}
}
// 使用示例
$resetter = new DatabaseResetter('localhost', 'test_db', 'root', 'password');
// 方式1: 执行SQL文件
$resetter->resetWithSqlFile('path/to/reset.sql');
// 方式2: 清空所有表
$resetter->cleanAllTables();
// 方式3: 使用事务回滚
$resetter->resetWithTransaction();
// 方式4: 从备份文件恢复
$resetter->restoreFromBackup('backup.sql');
?>
使用 PHPUnit 测试框架
<?php
use PHPUnit\Framework\TestCase;
class DatabaseTest extends TestCase {
private static $pdo;
private $transaction;
protected function setUp(): void {
// 开始事务
$this->transaction = self::$pdo->beginTransaction();
}
protected function tearDown(): void {
// 回滚事务,确保测试数据隔离
if ($this->transaction) {
self::$pdo->rollBack();
}
}
public function testDatabaseOperations() {
// 测试代码会自动在安全环境中运行
self::$pdo->exec("INSERT INTO users (name) VALUES ('测试用户')");
// 无论测试结果如何,都会回滚
}
}
?>
使用 ORM 提供的重置功能
Doctrine ORM
<?php // 使用 Doctrine SchemaTool $schemaTool = $entityManager->getConnection()->getSchemaManager(); $metadata = $entityManager->getMetadataFactory()->getAllMetadata(); $schemaTool->dropDatabase(); $schemaTool->createDatabase(); $schemaTool->createSchema($metadata); ?>
Laravel
<?php
// 在测试中
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\RefreshDatabase;
class ExampleTest extends TestCase {
use RefreshDatabase; // 每次测试后会重置数据库
public function test_example() {
// 测试代码
}
}
?>
使用备份恢复方案
<?php
function createBackup($db, $host, $user, $pass) {
// 创建数据库备份
$command = "mysqldump -h $host -u $user -p$pass $db > backup.sql";
exec($command);
}
function restoreBackup($db, $host, $user, $pass) {
// 从备份恢复
$command = "mysql -h $host -u $user -p$pass $db < backup.sql";
exec($command);
}
// 使用示例
createBackup('test_db', 'localhost', 'root', 'password');
// 测试后恢复
restoreBackup('test_db', 'localhost', 'root', 'password');
?>
最佳实践建议
- 使用事务回滚:测试时使用事务,测试后立即回滚
- 使用独立的测试数据库:不要在生产数据库上测试
- 自动化重置:编写自动化脚本,确保快速重置
- 保持测试数据独立:每个测试用例使用独立的测试数据
- 备份重要数据:测试前做好数据备份
选择哪种方法取决于你的项目需求和环境,最常用的是使用框架内置的迁移和种子数据功能,或者在测试中使用事务回滚来保证数据安全。