无效参数异常 - Laravel 单元测试

Invalid Argument Exception - Laravel Unit Testing

我是运行一个单元测试来检查

  1. 查看页面存在
  2. AssertSee 文本显示在页面上并且有字符串限制

我收到无效参数异常:

1) Tests\Feature\ViewAllPostTest::testCanViewAllPosts
InvalidArgumentException: You requested 1 items, but there are only 0 items available.

C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Support\Arr.php:472
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Support\Collection.php:1486
C:\projects\car-torque-laravel\database\factories\PostFactory.php:12
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:274
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:292
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\GuardsAttributes.php:122
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:300
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:219
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:178
C:\projects\car-torque-laravel\tests\Feature\ViewAllPostTest.php:19

我的源码如下:

测试函数

namespace Tests\Feature;

use App\Post;
use Tests\TestCase;

class ViewAllPostTest extends TestCase
{

    /**
     * @group posts
     *
     * @return void
     */
    public function testCanViewAllPosts()
    {
        //arrange
        $post = factory(Post::class)->create();

        //action
        $response = $this->get('/posts');

        //assert
        $response->assertStatus(200);
        $response->assertSee($post->body);
        $response->assertSee(str_limit($post->body));

    }
}

工厂Class

use App\Post;
use App\User;
use Faker\Generator as Faker;

$factory->define(Post::class, function (Faker $faker) {
    return [
        'body' => $faker->text,
        'user_id' => User::all()->random()->id,
        'created_at' => now(),
        'updated_at' => now(),
    ];
});

'user_id' => User::all()->random()->id,

在您工厂的上述行中,您需要来自用户的随机 ID table。但是你在 运行 测试之前创建了任何用户吗?在使用 post 工厂创建 post 之前,至少应该创建一个用户。