How can PHPUnit be used to prevent database changes during testing?
To prevent database changes during testing with PHPUnit, we can utilize transactions. By wrapping our test methods in transactions, any changes made to the database during the test will be rolled back at the end, ensuring the database remains unchanged.
class DatabaseTest extends \PHPUnit\Framework\TestCase
{
protected $pdo;
public function setUp(): void
{
$this->pdo = new \PDO('mysql:host=localhost;dbname=testdb', 'username', 'password');
$this->pdo->beginTransaction();
}
public function tearDown(): void
{
$this->pdo->rollBack();
}
public function testDatabaseChanges(): void
{
// Test logic that involves database changes
}
}