在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/