php - 不能使用 Illuminate\Contracts\Auth\Authenticatable - 这不是一个特征
问题描述
我尝试使用 jwtToken 测试我的应用程序的登录和注销。我迷失了 Laravel Contract 和 Trait。我阅读了很多问题/答案,但解决方案无法在我的代码上运行。我知道合同不像特质那样工作,但它似乎有很大的联系。自3天以来,我一直在寻找出路,但没有成功。
我有这个错误,因为我把 ActingAs 放在我的测试中。
你能帮我吗 ?
我的用户模型:
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Auth\UserInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Models\Role;
use App\Models\UserAddress;
class User extends Authenticatable implements
JWTSubject,
AuthenticatableContract
{
use Notifiable;
use SoftDeletes;
use Authenticatable;
我也尝试不implements AuthenticatableContract
使用我也尝试不使用第一次使用,不使用第二次使用。
我的测试用例:
namespace Tests;
use App\Models\Role;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
/**
* @var User
*/
protected $user;
public static $admin;
public static $faker;
public function setUp(): void
{
parent::setUp();
self::$faker = \Faker\Factory::create('fr_FR');
self::$admin = \App\Models\User::with('role')
->select('*')
->join('roles', 'roles.id_role', '=', 'users.id_role')
->where('slug', 'admin')
->first()->user;
我的帐户测试:
namespace Tests\Feature;
use Carbon\Carbon;
use Tests\TestCase;
use App\Models\Role;
use App\Models\User;
use Tymon\JWTAuth\JWTAuth;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Contracts\Auth\Authenticatable;
[...]
public function testLogout() {
// $user = User::inRandomOrder()->firstOrFail();
// \Log::debug('user->first_name : ' . $user->first_name);
$this->actingAs(self::$admin)
->json('POST', 'api/auth/logout')
->assertStatus(200);
}```
解决方案
这是不正确的:
class User extends Authenticatable implements
JWTSubject,
AuthenticatableContract
{
use Notifiable;
use SoftDeletes;
use Authenticatable;
}
你不能extend Authenticatable
和use Authenticatable
。
Authenticatable
不是特征(如错误所述)。它是一个抽象类,只能扩展。
您可以在此处阅读有关特征和抽象类之间区别的更多信息:PHP 中特征与抽象类之间的区别
删除该use
语句应该可以解决您的问题。
推荐阅读
- java - 在抽象类上获取自定义 bean
- android - 将应用程序从 28 定位到 29 后的 Android 下载管理器 - setDestinationInExternalPublicDir() - 不是标准目录之一:MyDir/videos/
- javascript - 如何使用 AngularFireDatabase 以更好的方式查询列表?
- python - discord.py SQLite 获取行内容
- javascript - Infinitegrid 重复 API 调用
- python - 在 BigQuery 中随机生成主键 (ID) 时如何避免插入重复行
- javascript - 如何使用 Javascript 或 jquery 在样式之间切换
- google-cloud-run - 如何使用 Google Cloud Run 缓存数据库查询?
- javascript - Discord.js --- TypeError:无法读取未定义的属性“执行”
- javascript - React:动态嵌套路由中的问题。如何解决这个错误?