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


How to test namespaced objects in Laravel 4 with phpunit

我正在组织我的测试文件夹以反映我的应用程序中的命名空间对象和接口。但是,在使用命名空间练习 TDD 时,我一直在尝试维持秩序时遇到麻烦!我完全不知道如何让所有这些作品都玩得好听。对此问题的任何帮助将不胜感激!

结构:

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

app/Acme/User.php

<?php namespace Acme;
use Eloquent;
class User extends Eloquent {
    protected $guarded = array();
    public static $rules = array();
}

app/tests/Acme/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表示法是在 PHP 5.5 中引入

<?php
use Acme'User;
class UserTest extends TestCase
{
    public function testCanBeLoaded()
    {
        $this->assertInstanceOf(User::class, new User);
    }
}

更新 22/11/2015

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