如果您正在测试 PHP 代码和 MySQL 数据库之间的交互,那么您正在执行集成测试,而不是单元测试。
下面是一些使用Enhance PHP 框架进行集成测试的示例,它测试一个存储库类,该存储库类保存和检索租户对象。
它不是针对预先填充的数据库运行,而是在完全空的数据库上运行,并使用简单的表帮助程序在运行时创建和销毁表。这消除了对特定数据在测试数据库中处于正确状态的依赖,这很难保持同步。
<?php
class TenantRepositoryTestFixture extends EnhanceTestFixture {
private $Target;
public function SetUp() {
$tables = new TableHelper();
$tables->CreateTenantTable();
$this->Target = Enhance::GetCodeCoverageWrapper('TenantRepository');
}
public function TearDown() {
$tables = new TableHelper();
$tables->DropTenantTable();
}
public function SaveWithNewTenantExpectSavedTest() {
$tenant = new Tenant();
$tenant->Name = 'test';
$saved = $this->Target->Save($tenant);
$result = $this->Target->GetById($saved->Id);
Assert::AreNotIdentical(0, $result->Id);
Assert::AreIdentical($tenant->Name, $result->Name);
}
public function SaveWithExistingTenantExpectSavedTest() {
$tenant = new Tenant();
$tenant->Name = 'test';
$saved = $this->Target->Save($tenant);
$saved->Name = 'changed';
$saved = $this->Target->Save($saved);
$result = $this->Target->GetById($saved->Id);
Assert::AreIdentical($saved->Id, $result->Id);
Assert::AreIdentical($saved->Name, $result->Name);
}
}
?>