【问题标题】:PHPUnit cannot find classes namespacePHPUnit 找不到类命名空间
【发布时间】:2015-12-12 11:45:26
【问题描述】:

我正在尝试使用 PHPUnit 运行一些单元测试,但是,当我使用命令行进行测试时,我的测试类无法从我的主类中找到命名空间。

这是我的文件夹结构:

data/ 
src/
    Dao/
    Entity/
        City.php
    Facade/
    SplClassLoader.php 
tests/
    Entity/
        CityTest.php
    bootstrap.php
    phpunit.xml 
vendor/ 
composer.json 
composer.lock

这是我在 /src/Entity/ 中的一个类的内容

<?php

namespace Entity;

class City
{
    /**
     * @var int
     */
    private $id;

我的 phpunit.xml

<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="../vendor/autoload.php">
    <testsuites>
        <testsuite name="Application Test">
            <directory>tests</directory>
        </testsuite>
    </testsuites>
</phpunit>

还有我的 CityTest.php

<?php

class CityTest extends PHPUnit_Framework_TestCase
{
    public function testAdd()
    {
        $city = new Entity\City(1, "London");
    }
}

当我运行命令 phpunit tests/Entity/CityTest.php 时,我收到此消息错误:

PHP 致命错误:找不到类 'Entity\City'

我可以做些什么来解决这个问题?

谢谢。

更新

我已经通过一些更新解决了我的问题。这是我的最终文件夹结构:

data/  
src/  
tests/  
vendor/
composer.json*  
composer.lock*
phpunit.xml*

phpunit.xml

<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="vendor/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
        >
    <testsuites>
        <testsuite name="Application Test Suite">
            <directory>./tests/</directory>
        </testsuite>
    </testsuites>
</phpunit>

composer.json

"require-dev": {
    "phpunit/phpunit": "4.8.*"
  },

  "config": {
    "process-timeout": 600,
    "preferred-install": "dist",
    "github-protocols": ["https"]
  },

  "autoload": {
    "psr-4": {
      "": "src/"
    }
  },

【问题讨论】:

    标签: php namespaces phpunit


    【解决方案1】:

    想法是使用“自动加载”将项目的源代码添加到 Composer。

    https://getcomposer.org/doc/01-basic-usage.md#autoloading

    【讨论】:

      猜你喜欢
      • 2013-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-30
      • 2016-07-05
      • 2013-03-25
      • 2012-10-23
      • 1970-01-01
      相关资源
      最近更新 更多