phpunit - testsuite 的名称可以与现有 class 相同吗?

phpunit - can name of testsuite be the same as existing class?

我创建了一套 php 脚本,它们执行许多 'Memcached' 操作,并且我已经为这个套件编写了 php 单元测试。测试套件名称为Memcachedphpunit.xml.dist文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true">
    <testsuites>
        <testsuite name="Memcached">
            <directory>./test</directory>
        </testsuite>
    </testsuites>
</phpunit>

但是,当我 运行 这个带有 --testsuite=Memcached 标志的测试套件时,我收到以下错误:

PHP Fatal error:  Uncaught PHPUnit\Framework\Exception: Class "Memcached" does not extend PHPUnit\Framework\TestCase.

错误可能是因为 php 已经有一个名为 Memcached 的 class。

如果我在 XML 文件中将测试套件重命名为 MemcachedTest,并且 运行 带有 --testsuite=MemcachedTest 标志的测试,单元测试 运行并以零错误完成。

我宁愿将测试套件命名为 Memcached,因为这将匹配我们其他测试套件的格式。

'phpunit' 的测试套件能否与现有的 class 命名相同?

您的测试 classes 需要扩展 \PHPUnit_Framework_TestCase class

<?php
/**
 * Class SomeTest.
 */
class SomeTest extends \PHPUnit_Framework_TestCase
{
    public function testSomething()
    {
        // test case
    }
}

查看文档 https://phpunit.de/manual/current/en/writing-tests-for-phpunit.html

回答你的问题:

Can test suites for 'phpunit' be named the same as an existing class?

,但前提是 class 是测试套件实现。

否则,

您 运行 陷入这个问题的原因是:

If the test suite name is a name of an existing class, the class will be instantiated as a test suite.

Memcached 显然不是 PHPUnit 测试套件。

另一方面:

If the test suite is just a string, an empty TestSuite object will be created with the given name.

要解决您的问题,请为测试套件指定一个非 class 名称:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true">
    <testsuites>
        <testsuite name="Memcached Tests">
            <directory>./test</directory>
        </testsuite>
    </testsuites>
</phpunit>

您遇到的行为实际上是 documented in the PHPUnit\Framework\TestSuite class:

/**
 * Constructs a new TestSuite:
 *
 *   - PHPUnit\Framework\TestSuite() constructs an empty TestSuite.
 *
 *   - PHPUnit\Framework\TestSuite(ReflectionClass) constructs a
 *     TestSuite from the given class.
 *
 *   - PHPUnit\Framework\TestSuite(ReflectionClass, String)
 *     constructs a TestSuite from the given class with the given
 *     name.
 *
 *   - PHPUnit\Framework\TestSuite(String) either constructs a
 *     TestSuite from the given class (if the passed string is the
 *     name of an existing class) or constructs an empty TestSuite
 *     with the given name.
 *
 * @param mixed  $theClass
 * @param string $name
 *
 * @throws Exception
 */