PHPUnit 类无法找到自身



PHPUnit 和测试新手,并一直遵循Teamtree House的指南。但我被困在这一点上,想知道是否有人可以提供帮助。以下是我文件中的详细信息:

phpunit.xml --- 在根目录中

<phpunit backupGlobals="true" bootstrap="tests/bootstrap.php">
<!-- Blacklist the vendor folder -->
<filter>
<blacklist>
<directory>vendor</directory>
</blacklist>
</filter>
<!-- Add the main testsuite -->
<testsuite>
<directory>tests</directory>
</testsuite>
</phpunit>

bootstrap.php --- in ./tests/bootstrap.php

<?php
// Get autoloader
require './vendor/autoload.php';
// Get tests
require './tests/PigLatinTest.php';
// Initialise twig
$loader = new Twig_Loader_Filesystem('./src');
$twig = new Twig_Environment($loader);

PigLatinTest.php --- in ./tests/PigLatinTest.php

<?php
require 'vendor/autoload.php';
require 'src/PigLatin.php';
class PigLatinTest extends PHPUnitFrameworkTestCase
{
/**
* @test PigLatin
*/
public function englishToPigLatinWorksCorrectly()
{
/**
* Given I have an english word
* If I pass that word to my PigLatin converter
* I get back the correctly transformed version
*/
$word = 'test';
$expectedResult = 'esttay';
$pigLatin = new PigLatin();
$result = $pigLatin->convert($word);
$this->assertEquals(
$expectedResult,
$result,
"PigLatin conversion did not work correctly"
);
}
}

PigLatin.php --- in ./src/PigLatin.php

<?php
class PigLatin
{
public function convert($word)
{
// Remove first letter of the word
$first_letter = substr($word, 0, 1);
$new_word = substr($word, 1, strlen($word) - 1);
$new_word .= $first_letter . 'ay';
return $new_word;
}
}

当我在终端中运行命令phpunit时,我得到以下输出:

PHPUnit 6.2.3 by Sebastian Bergmann and contributors.
Time: 68 ms, Memory: 10.00MB
No tests executed!

但是当我运行phpunit PigLatinTest时.php我收到以下错误:

PHP Fatal error:  Uncaught PHPUnitRunnerException: Class 'PigLatinTest' could not be found in 'PigLatinTest.php'. in phar:///usr/local/bin/phpunit/phpunit/Runner/StandardTestSuiteLoader.php:101

这真的让我感到困惑,我根本找不到关于SO的解决方案。如果有人有一些见解,将不胜感激!

您的问题在于所有包含。他们试图包含错误的文件。

测试/引导.php

<?php
// Let's use absolute paths instead with the help of __DIR__ which
// will give us the path to the current folder.
require __DIR__ . '/../vendor/autoload.php'; // Up one folder where the vendor is
// Removed the include for PigLatinTest since PHPUnit will handle that.
// Again, let's use __DIR__ to solve the path issues.
$loader = new Twig_Loader_Filesystem(__DIR__ . '/../src');
$twig = new Twig_Environment($loader);
// If your PigLatin-class isn't loaded with autoloading (in your composer.json),
// let's include it in here. Again, with the help of __DIR__
require __DIR__ . '/../src/PigLatin.php';

tests/PigLatinTest.php
在您的测试类中,我们可以删除所有include。引导程序已经处理好了。

结论请务必记住,如果包含/
要求包含/需要其他文件的文件,则所有相对路径都将相对于执行包含的文件,而不是文件本身。最好的方法是:require __DIR__ . '/relative/from/this/file.php。魔术常量__DIR__为您提供写入文件的绝对路径。

将文件包含在项目中一次后,可以在请求的其余部分访问该文件中的所有类和函数。无需多次包含它。

最新更新