使用 PHPUnit 进行 Laravel 测试断言顺序正确

Fra*_*ost 4 php testing phpunit laravel

我已经定义了一个范围,它通过published_at时间戳对我的实体进行排序。我想编写一个测试来确保正确的排序。

然而,我不知何故未能找到一种“好”的方法来做到这一点。

$novels = Novel::published()->get();
Run Code Online (Sandbox Code Playgroud)

这是我最好的猜测

for($i = 1; $i < count($novels); $i++) 
{
    $this->assertGreaterThanOrEqual(
        $novels->toArray()[$i - 1]['published_at'], 
        $novels->toArray()[$i]['published_at']
    );
}
Run Code Online (Sandbox Code Playgroud)

谁能提供更好的方法吗?

Rwd*_*Rwd 5

如果测试有效,那么您在测试中所做的事情没有任何问题。

话虽这么说,如果你想缩短测试时间,你可以这样做:

$this->assertEquals(
    $novels->pluck('id'),
    $novels->sortBy('published_at')->pluck('id'),
    'The Novels are not being ordered by published_at date'
);
Run Code Online (Sandbox Code Playgroud)