【问题标题】:phpunit - can name of testsuite be the same as existing class?phpunit - 测试套件的名称可以与现有类相同吗?
【发布时间】:2018-06-10 07:52:18
【问题描述】:

我创建了一套 php 脚本,它执行许多“Memcached”操作,并且我已经为这个套件编写了 phpunit 测试。测试套件名称为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的类。

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

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

'phpunit' 的测试套件可以与现有类命名相同吗?

【问题讨论】:

  • 你的测试用例类是如何命名的?
  • 测试用例类的类名带有Test。例如:MemcachedTestParserTest 等。即使套件中没有任何单元测试,由于套件被命名为Memcached,套件仍然会失败。
  • 我刚刚尝试使用 PHPUnit 6.5.5,一切正常。您的设置或环境一定有问题。我建议您尝试创建一个简单的项目来重现您的问题并将其发布,以便其他人可以查看他们是否也可以重现该问题。要回答您的问题“'phpunit' 的测试套件可以与现有类命名相同吗?” - 是的,类和测试套件名称之间没有联系。
  • 当你在你的服务器上尝试时,\Memcached 是一个有效的类名吗?
  • 我没有 Memcached。安装扩展程序后,我确实可以确认您的问题是合法的。我刚刚发布了一个答案,解释了为什么会发生这种情况。

标签: php unit-testing class phpunit test-suite


【解决方案1】:

回答你的问题:

“phpunit”的测试套件可以与现有类命名相同吗?

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

否则,

您遇到此问题的原因是:

如果测试套件名称是现有类的名称,则该类将被实例化为测试套件。

Memcached 显然不是 PHPUnit 测试套件。

另一方面:

如果测试套件只是一个字符串,则会使用给定名称创建一个空的 TestSuite 对象。

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

<?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
 */

【讨论】:

  • 非常感谢您对此进行调查;我很感激这个答案。我希望我们可以将我们的测试套件命名为与现有类相同,以与我们的其他套件保持一致,但 c'est la vie。
【解决方案2】:

您的测试类需要扩展 \PHPUnit_Framework_TestCase

<?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

【讨论】:

  • 我的测试类确实扩展了PHPUnit\Framework\TestCase
猜你喜欢
  • 2014-09-21
  • 1970-01-01
  • 1970-01-01
  • 2018-12-27
  • 2018-04-06
相关资源
最近更新 更多