无法在 phpunit 测试目录中实例化对象


Unable to instanciate object within phpunit testdirectory

我试图弄清楚phpunit,但是当我尝试在tesfile中实例化一个对象时,我不断收到以下错误:

Fatal error: Class stats'Baseball not found in c:'xampp'htdocs'stats'Test'BaseballTest.php

我有以下结构:

根/棒球.php

namespace stats;
class Baseball {
    //some code
}

根/phpunit.xml

<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true" bootstrap="vendor/autoload.php">
    <testsuites>
        <testsuite name="Application Test Suite">
            <directory>./Test/</directory>
        </testsuite>
    </testsuites>
</phpunit>
根/测试

/棒球测试.php

namespace stats'Test;
use stats'Baseball;
class BaseballTest extends 'PHPUnit_Framework_TestCase {
     $baseball = new Baseball(); // doesn't work
}

root/composer.json

{
    "require": {
    },
    "require-dev": {
        "phpunit/phpunit": "*"
    },
    "autoload": {
        "psr-0": {
            "stats": ""
        }
    }
}

(统计信息文件夹是根目录。

当我BaseballTest.php移出测试文件夹并将其放入根目录时,它似乎工作正常。我正在使用作曲家来执行

如果你们能帮助我,那就太好了!

提前感谢!

使用当前目录布局和作曲家配置,Baseball类应位于stats目录中。

您可以将其保留在根目录中,但需要切换到 psr-4 自动加载器,它允许您跳过命名空间映射中包含的目录:

{
    "require": {
    },
    "require-dev": {
        "phpunit/phpunit": "*"
    },
    "autoload": {
        "psr-4": {
            "stats''": ""
        }
    }
}

命名空间前缀名称处的尾部斜杠很重要 ( stats'' )。

有关自动加载标准的更多信息:

  • http://www.php-fig.org/psr/psr-4/
  • http://www.php-fig.org/psr/psr-0/
  • https://seld.be/notes/psr-4-autoloading-support-in-composer

我还建议您使用更标准的目录布局。将类放入src目录中,将测试放入tests目录中。命名空间大多是大写的。下面是它的外观:

<?php
// src/Baseball.php
namespace Stats;
class Baseball
{
}
<?php
// tests/BaseballTest.php
namespace Stats'Tests;
use Stats'Baseball;
class BaseballTest extends 'PHPUnit_Framework_TestCase
{
    public function testIt()
    {
        $baseball = new Baseball();
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true" bootstrap="vendor/autoload.php">
    <testsuites>
        <testsuite name="Application Test Suite">
            <directory>./tests/</directory>
        </testsuite>
    </testsuites>
</phpunit>
{
    "require": {
    },
    "require-dev": {
        "phpunit/phpunit": "*"
    },
    "autoload": {
        "psr-4": {
            "Stats''": "src"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Stats''Tests''": "tests"
        }
    }
}