在作曲家和phpunit中找不到类"sample \ question2 \ Hello" [英] Class 'sample\question2\Hello' not found with composer and phpunit

查看:75
本文介绍了在作曲家和phpunit中找不到类"sample \ question2 \ Hello"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用composer和phpunit,但出现错误找不到类".

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

目录结构:

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

并创建了composer.json

And created composer.json

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

我这样安装作曲家.

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

Hello.php就是这样.

Hello.php is like this.

<?php
namespace sample\question;

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

?>

test/HelloTest.php就是这样.

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.

推荐答案

您正在正确引导带有--bootstrap vendor/autoload.php的PHPUnit,以获取通过Composer生成的自动加载器自动加载的文件,但是

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

您的composer.json文件缺少autoloadautoload-dev部分.

{
    "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/"}
    }
}

,然后使用composer dump-autoload重新转储/重新生成Composer Autoloader.

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/

然后变成

"autoload": {
    "psr-4": {"sample\\question\\": "src/"}
}
"autoload-dev": {
    "psr-4": {"sample\\question\\tests\\": "tests/"}
}

这篇关于在作曲家和phpunit中找不到类"sample \ question2 \ Hello"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆