在 Laravel 中重现随机测试(使用 Faker)
Reproduce random tests in Laravel (using Faker)
在我们的一个项目中,我们遇到了随机的测试失败,当重新运行它们时,它们往往会再次成功。
我们使用 Laravel 5.8 和 phpunit 进行测试,在我们的测试中,我们经常使用工厂和 Faker 为数据库播种。
所以我想知道,是否可以在测试结束时(尤其是当测试失败时)打印 Faker 用来生成值的种子?所以我可以在 运行 测试之前设置这个种子,这样我就可以重现错误?
经过更多检查,我发现 faker 在内部使用 mt_rand
。
所以我所做的是在 setUp
中的每个测试开始时设置种子,然后在 tearDown
中打印它:
abstract class TestCase extends BaseTestCase
{
protected $seed;
protected function tearDown(): void
{
// Print seed so we know which one was used for this failing test
if ($this->hasFailed()) {
echo $this->seed;
}
}
protected function setUp(): void
{
// Seed the random seed for this test, so we can easily reproduce the same result, used seed will be printed when test fails
$this->seed = rand();
mt_srand($this->seed);
}
}
然后它将打印每个失败测试的种子,并在调试时重现只需将 $this->seed = rand();
替换为 $this->seed = the seed;
。
在我们的一个项目中,我们遇到了随机的测试失败,当重新运行它们时,它们往往会再次成功。
我们使用 Laravel 5.8 和 phpunit 进行测试,在我们的测试中,我们经常使用工厂和 Faker 为数据库播种。
所以我想知道,是否可以在测试结束时(尤其是当测试失败时)打印 Faker 用来生成值的种子?所以我可以在 运行 测试之前设置这个种子,这样我就可以重现错误?
经过更多检查,我发现 faker 在内部使用 mt_rand
。
所以我所做的是在 setUp
中的每个测试开始时设置种子,然后在 tearDown
中打印它:
abstract class TestCase extends BaseTestCase
{
protected $seed;
protected function tearDown(): void
{
// Print seed so we know which one was used for this failing test
if ($this->hasFailed()) {
echo $this->seed;
}
}
protected function setUp(): void
{
// Seed the random seed for this test, so we can easily reproduce the same result, used seed will be printed when test fails
$this->seed = rand();
mt_srand($this->seed);
}
}
然后它将打印每个失败测试的种子,并在调试时重现只需将 $this->seed = rand();
替换为 $this->seed = the seed;
。