【发布时间】:2015-03-19 04:37:13
【问题描述】:
我已经全新安装了 Laravel 5.0,但我遇到了 phpunit 测试的问题。 如果我为用户模型创建测试,我会收到错误 - 找不到用户类。
如果我测试控制器,工作正常,控制器类就会被检测到。
作为一种临时解决方法,只是为了测试它是否有效,我在 UserTest.php 中添加了 User 类。
我尝试在 app 文件夹中添加文件夹模型,将类放在里面,就像在 Laravel 4.2 中一样,也更改了 composer.json,运行 composer dump-autoload,但它没有工作。
"autoload": {
"classmap": [
"database",
"app/model"
],
"psr-4": {
"App\\": "app/",
}
},
简单的类如下所示:
// tests/models/UserTest.php
class UserTest extends TestCase
{
protected $user;
public function setUp()
{
parent::setUp();
}
public function testEmptyNameFailExpected()
{
$user = new User;
$user->name = '';
$result = $user->isValid();
$this->assertFalse($result);
return $user;
}
}
这里是 app 文件夹中的 User.php 类(在 laravel 5.0 中架构不同)
// app/User.php
namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Support\Facades\Validator;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
use Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name', 'email', 'password'];
public static $rules = [ 'name' => 'required|min:3' ];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
/**
* validate input
*
* @return bool
*/
public function isValid()
{
$validation = Validator::make($this->attributes, static ::$rules);
if ($validation->passes()) return true;
$this->errors = $validation->messages();
return false;
}
}
【问题讨论】:
-
尝试使用模型的 FQN。在您的情况下,它可能是
App\User -
我试过了,还是没有被识别。它在测试文件夹中搜索类,所以我认为自动加载的东西不好
-
@davidxd33 今天这有效,不知道为什么昨天没有