Laravel 单元测试中内存耗尽
Memory exhaused in Laravel unit tests
我为我的控制器编写了单元测试。我的 class 是
class ApiControllerTest extends TestCase
它包含这样的测试方法
public function testAgeDistribution()
{
$response = $this->action(...,
['datasetName'=>'AgeDistribution',
'min_longitude'=>-80.60, 'max_longitude'=>-78.60,
'min_latitude'=>43.20, 'max_latitude'=>44,
'zoom'=>12
]);
$this->assertResponseOk();
$json = json_decode($response->content());
$this->checkMainThings($json, 'AgeDistribution', 'Population', 7, 100, 7);
}
所有方法都相似,但参数和检查不同。
在处理函数的开头我有一行
$start_memory = memory_get_usage();
而且我看到(在调试器中)每个新测试都使用了越来越多的内存。
换句话说,测试之间不会释放内存。
如何在 PHP 中释放内存或者我在测试方法中有什么潜在的错误?
PHPUnit 不会自行清理。一种选择是扩展 TestCase 并释放 tearDown
:
中的内存
abstract class TestCase extends Illuminate\Foundation\Testing\TestCase
{
public function tearDown()
{
parent::tearDown();
$refl = new ReflectionObject($this);
foreach ($refl->getProperties() as $prop) {
if (!$prop->isStatic() && 0 !== strpos($prop->getDeclaringClass()->getName(), 'PHPUnit_')) {
$prop->setAccessible(true);
$prop->setValue($this, null);
}
}
}
}
我为我的控制器编写了单元测试。我的 class 是
class ApiControllerTest extends TestCase
它包含这样的测试方法
public function testAgeDistribution()
{
$response = $this->action(...,
['datasetName'=>'AgeDistribution',
'min_longitude'=>-80.60, 'max_longitude'=>-78.60,
'min_latitude'=>43.20, 'max_latitude'=>44,
'zoom'=>12
]);
$this->assertResponseOk();
$json = json_decode($response->content());
$this->checkMainThings($json, 'AgeDistribution', 'Population', 7, 100, 7);
}
所有方法都相似,但参数和检查不同。
在处理函数的开头我有一行
$start_memory = memory_get_usage();
而且我看到(在调试器中)每个新测试都使用了越来越多的内存。
换句话说,测试之间不会释放内存。
如何在 PHP 中释放内存或者我在测试方法中有什么潜在的错误?
PHPUnit 不会自行清理。一种选择是扩展 TestCase 并释放 tearDown
:
abstract class TestCase extends Illuminate\Foundation\Testing\TestCase
{
public function tearDown()
{
parent::tearDown();
$refl = new ReflectionObject($this);
foreach ($refl->getProperties() as $prop) {
if (!$prop->isStatic() && 0 !== strpos($prop->getDeclaringClass()->getName(), 'PHPUnit_')) {
$prop->setAccessible(true);
$prop->setValue($this, null);
}
}
}
}