传递给 Illuminate\Foundation\Testing\TestCase::actingAs() 的参数 1 必须实现接口 Illuminate\Contracts\Auth\Authenticatable

Argument 1 passed to Illuminate\Foundation\Testing\TestCase::actingAs() must implement interface Illuminate\Contracts\Auth\Authenticatable

传递给 Illuminate\Foundation\Testing\TestCase::actingAs() 的参数 1 必须实现接口 Illuminate\Contracts\Auth\Authenticatable,给定 Illuminate\Database\Eloquent\Collection 的实例

我也尝试了以下一些方法,但是 none 有效:

我希望有另一种方法可以解决这个问题。

这是我的 ClipartTest.php 文件:

<?php

namespace Tests\Feature;

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;

class ClipartTest extends TestCase
{
    use RefreshDatabase;

    /**
     * A basic feature test example.
     *
     * @return void
     */
    public function test_can_get_clipart()
    {
        $this->withoutExceptionHandling();

        $user = User::factory(3)->create();
        $this->actingAs($user, 'api');

        $this->getJson('/api/cliparts')
            ->assertStatus(201)
        ;
    }

这是我的 User.php 文件

<?php

namespace App\Models;

use App\Http\Traits\Uuid;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use Authenticatable, HasFactory, Notifiable, HasApiTokens;
    use Uuid;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

这是我的 Clipart.php 文件:

<?php

namespace App\Models;

use App\Http\Traits\Uuid;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Clipart extends Model
{
    use HasFactory;
    use Uuid;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id',
        'name',
        'image_id',
    ];

您正在使用工厂创建 3 个用户,因此 $user 实际上 return 是 3 个用户的集合。

而不是 User::factory(3)->create()User::factory()->create() 这样它将 return 一个单一的用户模型。