I created a suite of php scripts, which perform a number of 'Memcached' operations, and I have written phpunit tests for this suite. The name of the test suite is Memcached
, and the phpunit.xml.dist
file is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true">
<testsuites>
<testsuite name="Memcached">
<directory>./test</directory>
</testsuite>
</testsuites>
</phpunit>
However, when I run this test suite with the --testsuite=Memcached
flag, I receive the following error:
PHP Fatal error: Uncaught PHPUnit\Framework\Exception: Class "Memcached" does not extend PHPUnit\Framework\TestCase.
The error presumably occurs because php already has a class called Memcached
.
If I rename the testsuite to MemcachedTest
in the XML file, and run the tests with the --testsuite=MemcachedTest
flag, the unit tests run and complete with zero errors.
I would rather name the test suite Memcached
, as this would match the formatting of our other test suites.
Can test suites for 'phpunit' be named the same as an existing class?
To answer your question:
Can test suites for 'phpunit' be named the same as an existing class?
Yes, but only if the class is a test suite implementation.
Otherwise, no.
The reason why you're running into this issue is:
If the test suite name is a name of an existing class, the class will be instantiated as a test suite.
Memcached
is obviously not a PHPUnit test suite.
On the other hand:
If the test suite is just a string, an empty
TestSuite
object will be created with the given name.
To solve your issue, give the test suite a name that's not a class name:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true">
<testsuites>
<testsuite name="Memcached Tests">
<directory>./test</directory>
</testsuite>
</testsuites>
</phpunit>
The behaviour you've experienced is actually 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
*/