php - 错误 : Call to undefined function Tests\factory()

标签 php laravel

在laravel中,我编写了以下测试:

    public function testUserCanCreateAssortment()
    {
        $this->signIn();

        $this->get('/assortments/create')->assertStatus(200);

        $this->followingRedirects()
            ->post('/assortments', $attributes = Assortment::factory()->raw())
            ->assertSee($attributes['title'])
            ->assertSee($attributes['description']);
    }
}

当我使用命令 phpunit --filter testUserCanCreateItem 运行它时我收到以下错误:Error: Call to undefined function Tests\factory()不知道是什么原因造成的。我看过我的工厂和我的 testcase.php但我找不到解决方案。我究竟做错了什么?
我的 testcase.php :
<?php

namespace Tests;

use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;

    protected function signIn($user = null)
    {
        $user = $user ?: User::factory()->create();

        $this->actingAs($user);

        return $user;
    }
}
这里错误提供的行:/var/www/tests/TestCase.php:13/var/www/tests/Feature/ItemTest.php:29

最佳答案

在 Laravel 8 中,factory助手不再可用。您的 testcase模型类应该使用 HasFactory 特性,然后你可以像这样使用你的工厂:

testcase::factory()->count(50)->create();
请注意,您还应该更新对用户工厂的调用: factory('App\User')->create()->id;
以下是相关文档:
https://laravel.com/docs/8.x/database-testing#creating-models
但是,如果你更喜欢使用 Laravel 7.x 风格的工厂,你可以使用包 laravel/legacy-factories 你可以用 composer 安装它:
composer require laravel/legacy-factories

关于php - 错误 : Call to undefined function Tests\factory(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64538736/

相关文章:

php - 使用谷歌地图显示地理位置 x 英里范围内的范围地址

php - 合并两个查询并将返回添加到数组

php - 如何在 Controller 中显示验证消息?

php - 未选中的复选框值以更新请求

laravel 播种机数组到字符串的转换

php - Laravel - 使用复选框将数据发送到数据透视表

php - AJAX/本地存储 : Is it possible to pass a JS variable to PHP?

php - 上传到新创建的目录

PHP 和 MySQL - 唯一的列集

php - 没有连接 : Potential Security Issue laravel localhost on mac