【问题标题】:Static model class is null in feature test laravel静态模型类在功能测试 laravel 中为空
【发布时间】:2020-07-23 02:01:37
【问题描述】:

我在我的功能文件夹中有这个测试,我已经在类的顶部导入了模型,但它一直失败,我认为 $event 为空!

namespace Tests\Feature\Events;

use App\Models\Event;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;

class EventManagementTest extends TestCase
{
    use RefreshDatabase;

    /**
     * @test
     * @group event
     * A basic feature test to check event registration
     *
     */
    public function an_event_can_be_registered()
    {
        $this->withoutExceptionHandling();
        $response = $this->post('/events',$this->data());

        $event = Event::first();

        $this->assertCount(1,Event::all());
        $response->assertRedirect('/events/' . $event->event_id);
    }

    private function data()
    {
        return[
            'event_title'       => 'Internet Businesses',
            'event_location'    => 'Milad Tower',
            'event_description' => 'In this event Amin will present you the most recent methods in Internet Businesses',
            'event_start_date'  => '2020-06-01',
            'event_end_date'    => '2020-06-05',
        ];
    }
...
}

这是结果:

FAIL Tests\Feature\Events\EventManagementTest ✕ 可以注册一个事件

测试:1 次失败

断言两个字符串相等失败。 ....

--- 预期

+++实际

@@@@

-'http://localhost/events/1'

+'http://localhost/events'

这两个 URI 是不同的,我认为这是因为 $event 为空,我不知道为什么?!

更新:我添加了路由和控制器:

Route::post('/events','Web\EventsController@store');

控制器是:

public function store(){
        $event = Event::create($this->validateRequest());
        return redirect('/events/'.$event->event_id);
 }

protected function validateRequest(){
        return request()->validate([
            'event_title'       => 'required',
            'event_location'    => 'required',
            'event_description' => 'required',
            'event_start_date'  => 'required',
            'event_end_date'    => 'required',
        ]);
 }

【问题讨论】:

  • 我们能看到您呼叫的路线吗?
  • @mrhm 当然!我已经更新了问题
  • 您的事件模型看起来如何?
  • @mrhn 只是保护了事件 ID,例如:protected $guarded = ['event_id'];

标签: laravel phpunit


【解决方案1】:

您不使用标准的主 id 列,因此您需要在模型中定义它。如果未定义,则不会在create()上设置。

class Event extends Model {
    protected $primaryKey = 'event_id';
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 2019-11-17
    • 1970-01-01
    • 2019-07-27
    • 2018-01-22
    • 2021-09-07
    • 1970-01-01
    相关资源
    最近更新 更多