1

I use composer and phpunit but the error "Class not found" is appeared.

Directory Structure:

  • php_sample/sample/question/
  • php_sample/sample/question/Hello.php
  • php_sample/sample/question/tests/HelloTest.php

And created composer.json

{
    "require-dev": {
    "phpunit/phpunit": "4.5.*"
    }
}

I installed the composer like this.

$ curl -sS https://getcomposer.org/installer | php
$ ./composer.phar update
$ ./composer.phar install --dev

Hello.php is like this.

<?php
namespace sample\question;

class Hello
{
    public function hello()
    {
        return 'Hello, world';
    }
}

?>

test/HelloTest.php is like this.

<?php
namespace sample\question\tests;

use sample\question\Hello;

class HelloTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Hello
     */
    public $SUT;

    /**
     * @test
     */
    public function canPrint()
    {
        $this->assertThat($this->SUT->hello(), $this->equalTo('Hello, world'));
    }

    protected function setUp()
    {
        $this->SUT = new Hello;
    }
}

And then, I run the this script and the error is occurred.

$ vendor/bin/phpunit --bootstrap vendor/autoload.php tests/HelloTest.php


PHP Fatal error:  Class 'sample\question\Hello' not found in /Users/foobar/work/php_sample/sample/question/tests/HelloTest.php on line 32

It would be great if you answer to me.

masudak
  • 161
  • 1
  • 6

1 Answers1

2

You are correctly bootstraping PHPUnit with --bootstrap vendor/autoload.php to get the files autoloaded via the Composer generated autoloaders, but

your composer.json file misses the autoload and autoload-dev sections.

{
    "require-dev": {
        "phpunit/phpunit": "4.5.*"
    }
    "autoload": {
         "psr-4": {"sample\\question\\": "php_sample/sample/question/"}
    }
    "autoload-dev": {
         "psr-4": {"sample\\question\\tests\\": "php_sample/sample/question/tests/"}
    }
}

and then just re-dump/re-generate the Composer Autoloader with composer dump-autoload.


Sidenote: I'm not sure that the folder structure really works out..

Maybe its worth to change your project folder layout to:

project/src
project/tests

project/src/sample/question/
project/tests/sample/question/

then it becomes

"autoload": {
    "psr-4": {"sample\\question\\": "src/"}
}
"autoload-dev": {
    "psr-4": {"sample\\question\\tests\\": "tests/"}
}
Jens A. Koch
  • 39,862
  • 13
  • 113
  • 141
  • @jens-a-koch Thank you for your grateful and kind advice!! I've changed the structure of directories and modified compose.json, then it worked! It is necessary of composer settings for phpunit, isn't it? I didn't understand that, sorry. I fully appreciate your cooperation. – masudak Jan 13 '16 at 11:16
  • I'm glad i could help :) – Jens A. Koch Jan 13 '16 at 11:44