You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 8.83.18:模型为何提示‘Undefined property’错误?

问题分析:PHPUnit测试中出现「未定义属性」错误

场景描述

我以User身份对API运行Post测试,执行命令:

./vendor/bin/phpunit

终端返回如下错误:

There was 1 error:

1) Tests\Feature\PostTest::testStoreValid
ErrorException: Undefined property: Tests\Feature\PostTest::${"name":"Elfrieda Hoppe","email":"robert.krajcik@example.com","email_verified_at":"2022-08-15T05:24:00.000000Z","updated_at":"2022-08-15T05:24:00.000000Z","created_at":"2022-08-15T05:24:00.000000Z","id":1}

相关代码文件

TestCase.php

<?php namespace Tests;

use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use App\Models\User;

abstract class TestCase extends BaseTestCase
{ 
    use CreatesApplication;

    protected function user()
    {
        return User::factory()->create();
    }
}

PostTest.php

<?php namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class PostTest extends TestCase
{
    use RefreshDatabase;

    public function testStoreValid()
    {
        $user = $this->user();

        $params = [
            "title" => "Valid Title",
            "content" => "At least 10 characters",
        ];

        $this->actingAs($this->$user)
            ->post("/posts", $params)
            ->assertStatus(302)
            ->assertSessionHas("status");

        $this->assertEquals(session("status"), "the blog post was created!");
    }
}

User.php

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasFactory, Notifiable;
    
    protected $fillable = ["name", "email", "password"];
    protected $hidden = ["password", "remember_token"];
    protected $casts = [
        "email_verified_at" => "datetime",
    ];
}

UserFactory.php

<?php namespace Database\Factories;

use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class UserFactory extends Factory
{
    protected $model = User::class;

    public function definition()
    {
        return [
            "name" => $this->faker->name,
            "email" => $this->faker->unique()->safeEmail,
            "email_verified_at" => now(),
            "password" =>
                '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
            "remember_token" => Str::random(10),
        ];
    }
}

问题原因及解决方法

错误根源在PostTest.php的actingAs调用处:

$this->actingAs($this->$user)

这里多写了一个$符号,$this->$user会把$user变量的字符串值(也就是User对象的打印结果)当作测试类的属性名去查找,自然找不到对应属性,因此抛出「未定义属性」错误。

正确写法是直接传递$user变量:

$this->actingAs($user)

actingAs方法本身就接收用户模型实例作为参数,无需通过$this->访问。修改后重新运行测试即可解决问题。

内容的提问来源于stack exchange,提问作者joeleen-kado

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 13:42:22