【问题标题】:Laravel 5.0 phpunit modelsLaravel 5.0 phpunit 模型
【发布时间】: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 今天这有效,不知道为什么昨天没有

标签: php database laravel-5


【解决方案1】:

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

你说你的测试文件夹是

app/tests/models/UserTest.php

这是不正确的。在 Laravel 5.0 的全新安装中 - 测试类位于基本文件夹中 - 而不是 app 文件夹中 - 所以它应该是

tests/models/UserTest.php

另外 - 你的用户在 Laravel 5.0 中被命名空间 - 所以你的代码需要是

$user = new \App\User;

【讨论】:

  • 第一个问题 - 这是一个错字,我在测试文件夹中设置了它,对不起。其次,谢谢,今天早上我让它工作了。很奇怪,因为我昨天尝试了同样的事情并且根本没有工作。
猜你喜欢
  • 2018-05-25
  • 2021-12-23
  • 2017-09-04
  • 2016-01-08
  • 1970-01-01
  • 2021-06-27
  • 2014-08-16
  • 2013-06-29
  • 2018-03-03
相关资源
最近更新 更多