laravel中使用Faker时,如何测试[=10th=]课的成绩?

When using Faker in laravel, how to test the results of API calls?

我想为 Laravel 中的 API 调用编写测试。我创建了一个模型工厂来为我的测试数据库播种,因此 API 调用可以 return 一些东西。在模型工厂内部,我使用 Faker 为模型属性生成随机数据。我在测试开始时使用这个工厂,所以数据是在运行时创建的。

如何测试 API 调用的结果?问题是在每次执行测试期间,由于随机生成的数据,API 调用可能会 return 不同的结果。所以我不能只将 APi 调用的结果保存在 .json 文件中,并将其与测试中 API 调用的实际结果进行比较。

我知道 seeJsonStructure() 方法 ( https://laravel.com/docs/5.3/application-testing#verifying-structural-match ),但我不想使用它。

所以这是我目前的尝试,但没有成功:

$cars = factory(Car::class)->times(2)->create();

$this->json('GET', '/api/cars');

$expected = File::get('cars.json');

$this->seeJson((array) json_decode($expected));

您可以按照 here.

在 Faker 中设置种子值

Seeding the Generator

You may want to get always the same generated data - for instance when using Faker for unit testing purposes. The generator offers a seed() method, which seeds the random number generator. Calling the same script twice with the same seed produces the same results.

<?php
$faker = Faker\Factory::create();
$faker->seed(1234);

echo $faker->name; // 'Jess Mraz I';

这将使您在测试运行中得到一致的结果。