2015-01-20 134 views
1

我已經乾淨安裝Laravel 5.0,並且我有phpunit測試問題。 如果我爲用戶模型創建一個測試,我收到錯誤 - 找不到用戶類。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; 
    } 
} 

這裏是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; 
    } 

} 
+1

嘗試使用模型的FQN。在你的情況下,它可能是'App \ User' – davidxd33 2015-01-20 20:09:51

+0

我試過了,但仍然無法識別。它搜索測試文件夾內的類,所以我認爲自動加載的東西不好 – 2015-01-20 20:31:43

+0

@ davidxd33今天這工作,不知道爲什麼昨天沒有 – 2015-01-21 10:15:51

回答

3

我注意到2您的代碼存在問題:

您說你的測試文件夾是

app/tests/models/UserTest.php 

這是不正確的。在清潔Laravel 5.0的安裝 - 測試類是在基礎文件夾 - 而不是app文件夾 - 所以它應該是

tests/models/UserTest.php 

而且 - 您的用戶的命名空間中Laravel 5.0 - 所以你的代碼將需要

$user = new \App\User; 
+0

第一個問題 - 這是一個錯字,我在測試文件夾中設置它,對不起。第二,謝謝,今天早上我讓它工作。奇怪,因爲我昨天嘗試了同樣的事情,根本沒有工作。 – 2015-01-21 10:14:28