如何使用phpunit在Laravel 4中测试命名空间对象

前端之家收集整理的这篇文章主要介绍了如何使用phpunit在Laravel 4中测试命名空间对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在组织我的测试文件夹以反映我的应用程序中的命名空间对象和界面.但是,在使用命名空间练习TDD时,我一直在努力维护秩序.我完全不知道如何让所有这些作品发挥得淋漓尽致.任何有关此问题的帮助将不胜感激!

结构体:

app/ 
  Acme/ 
    Repositories/ 
      UserRepository.PHP 
    User.PHP
  tests/ 
    Acme/ 
      Repositories/ 
        UserRepositoryTest.PHP 
      UserTest.PHP

应用程序/ Acme公司/ user.PHP

<?PHP namespace Acme;

use Eloquent;

class User extends Eloquent {

    protected $guarded = array();

    public static $rules = array();
}

应用程序/测试/阿克米/ UserTest.PHP

<?PHP

use Acme\User;

class UserTest extends TestCase {

    public function testCanBeLoaded()
    {
        $this->assertInstanceOf(User,new User);
    }
}

PHPUnit结果:

1) UserTest::testCanBeLoaded
ErrorException: Use of undefined constant User - assumed 'User'

解决方法

assertInstanceOf方法需要一个字符串,而不是一个对象.试试User :: class. :: class表示法是 introduced in PHP 5.5

<?PHP

use Acme\User;

class UserTest extends TestCase
{
    public function testCanBeLoaded()
    {
        $this->assertInstanceOf(User::class,new User);
    }
}

2015年11月22日更新

使用当今PHP的最佳实践更新了我对更好解决方案的回答.

猜你在找的Laravel相关文章