如何通过PHP单元测试避免竞争条件

时间:2018-01-23 13:44:58

标签: php laravel testing laravel-5 phpunit

让我们从证明开始,这是我面临的竞争条件:

测试用例失败❌

phpunit --filter testMethod testlass path/to/testFile.php
PHPUnit 5.7.26 by Sebastian Bergmann and contributors.

F                                                                   1 / 1 (100%)

You should really fix these slow tests (>500ms)...
 1. 6441ms to run testClass::testMethod


Time: 6.49 seconds, Memory: 22.00MB

There was 1 failure:

1) ≈
Unable to find row in database table [orders] that matched attributes 
[{"collect_cash":104,"id":1728,"final_total":100}].
Failed asserting that 0 is greater than 0.

project/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithDatabase.php:24
path/to/testFile.php:78

FAILURES!
Tests: 1, Assertions: 2, Failures: 1.

这是运行和成功的相同测试,没有任何代码更改:

成功的测试用例✅

$ phpunit --filter method class path/to/testFile.php
PHPUnit 5.7.26 by Sebastian Bergmann and contributors.

.                                                                   1 / 1 (100%)

You should really fix these slow tests (>500ms)...
 1. 1631ms to run testClass::testMethod

Time: 1.68 seconds, Memory: 22.00MB

发生故障的地方

失败发生在它检查数据库记录的地方:

    $this->shopperPut("/some/api/call")
        ->seeApiSuccess();

    $this->seeInDatabase('orders', [
        'collect_cash'  => $order->final_total + $chargeFare,
        'id'            => $order->id,
        'final_total'   => $order->final_total,

/some/api/call我们这样做

    .. some logic

    $order->save();

    .. more logic

    return response()->success(compact('order'));

我尝试了什么

我已经尝试过安装睡眠命令..但这很麻烦,减慢了测试速度,最重要的是并不总是有效。

我还能做什么?

注意:这个问题不是关于许多使用相同数据库的开发人员。这严格在我的localhost上,事实上我正在使用专门用于单元测试的testDatabase。

1 个答案:

答案 0 :(得分:1)

我有没有竞争条件问题的测试。

$response = $this->get('/some/api/call');

$response->assertSessionHas('order');

$this-assertDatabaseHas('orders', [
    'collect_cash'  => $order->final_total + $chargeFare,
    'id'            => $order->id,
    'final_total'   => $order->final_total,
]);

https://laravel.com/docs/5.5/database-testing#introduction