简体   繁体   中英

Laravel : Use Eloquent Model in API Testing

I want to test api with real database insert and query, so I try to use setUpBeforeClass and tearDownAfterClass method for pre and after test process.

<?php

use App\Models\User;

class UserTest extends TestCase {

public static function setUpBeforeClass()
{
    User::create([ 'name' => 'Tom' ]);
}

public function testStore()
{
    $this->call('POST', 'users', [
        'name' => 'Tim'
    ]);

    $this->assertResponseOk();
}

public static function tearDownAfterClass()
{
    $users = User::where('name', '=', 'Tom')
               ->orWhere('name', '=', 'Tim')->get();

    $users->each(function($user) {

        $user->delete();
    });
}

}

But, when it will get Eloquent not found.

Fatal error: Class 'Eloquent' not found in /Applications/MAMP/htdocs/edu-api/apis/app/models/User.php on line 6

<?php namespace App\Models;

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

use Eloquent;

class User extends Eloquent {

Are there any mistakes I make with namespace or environment, or even I should not do this?

Eloquent is an alias for the Model class, so you need this:

use Illuminate\Database\Eloquent\Model as Eloquent;

class User extends Eloquent {

or simply extend the model without inline aliasing

use Illuminate\Database\Eloquent\Model;

class User extends Model {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM