Laravel 5.0 phpunit 模型

Laravel 5.0 phpunit models

我全新安装了 Laravel 5.0,但我遇到了 phpunit 测试问题。 如果我为用户模型创建测试,我会收到错误消息 - 未找到用户 class。

如果我测试控制器,工作正常,控制器 class 被检测到。

作为临时解决方法,只是为了测试它是否有效,我在 UserTest.php.

中添加了 class 用户

我尝试在应用程序文件夹中添加文件夹模型,将 class 放在里面,与 Laravel 4.2 中的类似,也更改了 composer.json,运行 composer转储自动加载,但它没有用。

"autoload": {
    "classmap": [
        "database",
        "app/model"
    ],
    "psr-4": {
        "App\": "app/",
    }
},

简单的 classes 看起来像这样:

// 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;
    }
}

这里是应用程序文件夹中的 User.php class(在 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;
    }

}

我注意到您的代码有两个问题:

你说你的测试文件夹是

app/tests/models/UserTest.php

这是不正确的。在 Laravel 5.0 的全新安装中 - 测试 class 位于基础文件夹中 - 而不是 app 文件夹中 - 因此它应该是

tests/models/UserTest.php

此外 - 您的用户在 Laravel 5.0 中命名空间 - 因此您的代码需要

$user = new \App\User;