简体   繁体   English

Laravel:在API测试中使用Eloquent模型

[英]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. 我想用真正的数据库插入和查询来测试api,所以我尝试使用setUpBeforeClasstearDownAfterClass方法进行前后测试过程。

<?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. 但是,当它没有找到Eloquent

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: EloquentModel类的别名,因此您需要:

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 {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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