我正在尝试编写一些简单的PHPUnit测试,以测试我的User class
和一些DB
查询。
我在每个数据库查询函数调用中都收到一个A facade has not been set
,但我不知道为什么。
我是否忘记导入或包含文件,或者无法使用laravel DB
类运行PHP单元?
UserTest.php
<?php
namespace Tests\Unit;
use App\User;
use Tests\TestCase;
class UserTest extends TestCase
{
const TABLENAME = 'user';
protected static $userid;
public static function setUpBeforeClass(): void
{
$user = new \stdClass();
$user->name = "Test 1";
$user->email = "[email protected]";
$user->password = "Password";
self::$userid = User::createNewUser($user);
}
/**
* Create a user
*
* @return void
*/
public function testGetUser(): void
{
$user = new User(self::$userid);
var_dump($user);
if (empty($user)) {
$this->assertTrue(false);
} else {
$this->assertTrue(true);
}
}
}
User.php
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\DB;
use StdClass;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name', 'email', 'password'];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = ['password'];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [];
private $id = 0;
private $username = null;
private $email = null;
private $createdAt = null;
private $updatedAt = null;
const TABLENAME = 'user';
public function __construct(int $userId)
{
$user = DB::table(self::TABLENAME)->where('id', $userId)->get();
$this->id = $user->id;
$this->username = $user->name;
$this->email = $user->email;
$this->createdAt = $user->createdAt;
$this->updatedAt = $user->updatedAt;
}
public function get(string $field): string
{
return $this->{$field};
}
public function updateUser(stdClass $user): boolean
{
$user->id = $this->id;
$result = DB::table(self::TABLENAME)->update((array) $user);
return ($result >= 1) ? true : false;
}
public static function createNewUser(stdClass $user): int
{
return DB::table(self::TABLENAME)->insertGetId((array) $user);
}
}