如何在phpunit中引用外部数据提供程序?

Edw*_*ard 3 php tdd phpunit symfony composer-php

我正在尝试使用PHPUnit中的通用数据提供程序来运行一些测试。

参见以下测试:

    namespace AppBundle\Tests\Controller;

    use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
    use AppBundle\Tests\DataProvider\XmlDataProvider;

    class DefaultControllerTest extends WebTestCase
    {
        /**
         * @dataProvider XmlDataProvider::xmlProvider
         * @covers ReceiveController::receiveAction()
         * @param string
         */
        public function testReceive($xml)
        {
            $client = static::createClient([], ['HTTP_HOST' => 'mt.host']);
            $client->request(
                'POST',
                '/receive',
                [],
                [],
                [],
                $xml
            );

            $response = $client->getResponse();
            $this->assertEquals(200, $response->getStatusCode());
        }
    }
Run Code Online (Sandbox Code Playgroud)

现在,我需要一个外部数据提供程序类:

namespace AppBundle\Tests\DataProvider;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class XmlDataProvider extends WebTestCase
{
    /**
     * @dataProvider
     */
    public static function xmlProvider()
    {
        return array([
            'xml1' => '<?xml version="1.0" encoding="UTF-8"?><myTestableXml></myTestableXml>'
        ]);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是当我运行phpunit时,我得到:

1)警告为AppBundle \ Tests \ Controller \ DefaultControllerTest :: testReceive指定的数据提供程序无效。XmlDataProvider类不存在

2)警告在类“ AppBundle \ Tests \ DataProvider \ XmlDataProvider”中未找到测试。

我该怎么做呢?

更新

composer.json自动加载代码段供参考:

"autoload": {
    "psr-4": {
        "AppBundle\\": "src/AppBundle",
        "Tests\\": "tests"
    },
    "classmap": [
        "app/AppKernel.php",
        "app/AppCache.php"
    ]
},
"autoload-dev": {
    "psr-4": {
        "Tests\\": "tests/"
    },
    "files": [
        "vendor/symfony/symfony/src/Symfony/Component/VarDumper/Resources/functions/dump.php"
    ]
},
Run Code Online (Sandbox Code Playgroud)

loc*_*inz 5

您需要使用完全限定的类名来引用数据提供者:

namespace AppBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DefaultControllerTest extends WebTestCase
{
    /**
     * @dataProvider \AppBundle\Tests\DataProvider\XmlDataProvider::xmlProvider
     * @covers ReceiveController::receiveAction()
     * @param string $xml
     */
    public function testReceive($xml)
    {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

自动加载

另外,请确保在中调整自动加载配置composer.json,以便可以自动加载数据提供程序(可能需要根据“ AppBundle \ Test”命名空间映射到的目录进行调整):

{
    "autoload-dev": {
        "psr-4": {
            "AppBundle\\Tests\\": "tests/"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

另外,由于您建议您的自动加载配置如下所示:

{
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您需要将提供的测试的命名空间从调整AppBundle\TestsTests\AppBundle

注意与您的问题无关,但就我个人而言,我认为数据提供程序不需要扩展WebTestCase

有关示例,请参见: