Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
669 views
in Technique[技术] by (71.8m points)

php - PHPUnit - autoload classes within tests

I have the following structure within my project:

/
/app
/app/models/ --UserTable.php

/lib
/lib/framework
/lib/framework/Models
/lib/framework/Db

/tests -- phpunit.xml, bootstrap.php
/tests/app
/tests/app/models --UserTableTest.php

With the app and lib directories I have various classes that work together to run my app. To setup my tests I have create a /tests/phpunit.xml file and a /tests/bootstrap.php

phpunit.xml

<phpunit bootstrap="bootstrap.php">
</phpunit>

bootstrap.php

<?php

function class_auto_loader($className)
{
  $parts = explode('\', $className);
  $path = '/var/www/phpdev/' . implode('/', $parts) . '.php';

  require_once $path;
}

spl_autoload_register('class_auto_loader');

So I have the following test:

<?php

class UserTableTest extends PHPUnit_Framework_TestCase
{
  protected $_userTable;

  public function setup()
  {
    $this->_userTable = new appmodelsUserTable;
  }

  public function testFindRowByPrimaryKey()
  {
    $user = $this->_userTable->find(1);

    $this->assertEquals($user->id, 1);
  }
}

But it can't find the class when I run the test - PHP Fatal error: Class 'appmodelsUserTable' not found in /var/www/phpdev/tests/app/models/UserTableTest.php on line 13

What am I doing wrong? I'm trying to understand PHPUnit configuration better so I opted to write the configuration and bootstrap file myself.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you are using composer autoload

change

<phpunit colors="true" strict="true" bootstrap="vendor/autoload.php">

to

<phpunit colors="true" strict="true" bootstrap="tests/autoload.php">

and in tests directory create new autoload.php with following content

include_once __DIR__.'/../vendor/autoload.php';

$classLoader = new ComposerAutoloadClassLoader();
$classLoader->addPsr4("Your\Test\Namespace\Here", __DIR__, true);
$classLoader->register();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...