Silex:使用PHPUnit的RouteNotFoundException - 无法为命名路由生成URL"主页"因为这样的路线不存在

时间:2016-10-31 19:34:22

标签: symfony routing phpunit silex

我在https://github.com/silexphp/Silex/issues/1442上问了这个问题,但我觉得这不一定是代码问题,所以我想我会扩展范围。

升级到silex 2和symfony 3以及其他所有......

路由包含在app.php的末尾,看起来像这样...

$app->get('/', 'queue.controller:indexAction')
->after(function (Request $request, Response $response, $app) {
    $response->setPublic();
    $response->setSharedMaxAge($app['cache']['s-maxage']);
})
->host($app['domains']['xxx'])
->bind('homepage');

这在浏览器中很好用,转到主页,工作正常。如果我正在运行phpunit但是...在尝试生成路由时出现以下错误...

Symfony\Component\Routing\Exception\RouteNotFoundException: Unable to generate a URL for the named route "homepage" as such route does not exist.

并且测试看起来像这样......

public function testTargetingOnHomepage()
{
    $client = $this->createClient();
    echo $this->app->url('homepage');
   .....
}

我很困惑为什么我的路线在从phpunit执行时没有被添加到应用程序。

测试用例类有......

class AdTargetControllerTest extends SomeWebTestCase

并且somewebtestcase.php看起来像......

<?php
namespace theapp\SomeFramework;

use Silex\WebTestCase;
use Fixtures\UserFixture;
use Symfony\Component\BrowserKit\Client;
use Symfony\Component\HttpFoundation\Session\Storage\MockFileSessionStorage;

class SomeWebTestCase extends WebTestCase
{
public $youtubeEmbed;
private $mockSessionDir;

public function createApplication()
{
    $appDir = __DIR__.'/../../..';
    $app = include "$appDir/app.php";

    $app['debug'] = true;
    $app['session.test'] = true;

    $this->mockSessionDir = $app['tmpdir']. '/mocksessions';
    $app['session.storage.test'] = function ($app) {
        return new MockFileSessionStorage($app['tmpdir']. '/mocksessions');
    };

    unset($app['exception_handler']);

    // Emails get stored in the mail "logger" ... not delivered.
    $app['mailer.logger'] = function ($app) {
        return new \Someecards\SomeFramework\MessageLogger();
    };

    // Force silex to use transport and not spooltransport
    $app['swiftmailer.use_spool'] = false;

    $app["swiftmailer.transport"] = function ($app) {
        return new \Swift_Transport_NullTransport($app['swiftmailer.transport.eventdispatcher']);
    };

    $app->extend('mailer', function ($mailer, $app) {
        $mailer->registerPlugin($app['mailer.logger']);
        return $mailer;
    });

    $this->youtubeEmbed = '<iframe width="480" height="270" src="https://www.youtube.com/embed/';
    $this->youtubeEmbed .= 'LDtHJYa6xu4?feature=oembed" frameborder="0" allowfullscreen></iframe>';

    // using Mockery since this library uses a static method for create
    $app['oembedMock'] = \Mockery::mock('alias:Embed\Embed');

    $app['oembedMock']
        ->shouldReceive('create')
        ->andReturn(
            (object) array(
                'title' => 'Oembed title',
                'description' => 'Oembed Description',
                'providerName' => 'YouTube',
                'code' => $this->youtubeEmbed,
                'type' => 'video',
                'author' => 'test',
                'authorUrl' => 'test',
                'width' => 500,
                'height' => 500,
                'image' => 'test',
                'imageWidth' => 500,
                'imageHeight' => 500
            )
        );

    $app->boot();
    return $app;
}

这里还有其他功能,但这是我相信的重要功能。

phpunit bootstraps with ...

<?php

use theapp\SomeFramework\TestingUtil;

// autoload libraries
require_once __DIR__.'/../thirdparty/vendor/autoload.php';
TestingUtil::init();

然后testingutil.php看起来像......

namespace Someecards\SomeFramework;

class TestingUtil
{
    public static function init()
    {
    // This if/else allows the phpunit processIsolation flag to be set to true.
    // We're not currently doing that because it slows things down three fold.
    // If you see errors about too many open connections/files you can run
    // ulimit -n 10000, try to close db connections and log files (couldn't fclose
    // these in tearDowns for some reason), or turn on processIsolation.
    if (!defined('PHPUNIT_HAS_BOOTSTRAPED')) {
        self::bootstrap();
        define('PHPUNIT_HAS_BOOTSTRAPED', true);
    }
    }

public static function bootstrap()
{
    $app = require __DIR__.'/../../../app.php';
    $app->boot();

    $dbOptions = $app['db.options'];
    if ($dbOptions['driver'] == 'pdo_sqlite') {
        $testdb = $dbOptions['path'];
        if (file_exists($testdb)) {
            @unlink($testdb);
        }

        $cacheDriver = $app['orm.em']->getConfiguration()->getMetadataCacheImpl();
        $cacheDriver->deleteAll();
        $cacheDriver = $app['orm.em']->getConfiguration()->getResultCacheImpl();
        $cacheDriver->deleteAll();
        $cacheDriver = $app['orm.em']->getConfiguration()->getQueryCacheImpl();
        $cacheDriver->deleteAll();

        $tool = new \Doctrine\ORM\Tools\SchemaTool($app['orm.em']);
        $classes = $app['orm.em']->getMetadataFactory()->getAllMetadata();
        $tool->createSchema($classes);

        $loader = new \Doctrine\Common\DataFixtures\Loader();
        $loader->loadFromDirectory(__DIR__ ."/../../Fixtures");
        $purger = new \Doctrine\Common\DataFixtures\Purger\ORMPurger();
        $executor = new \Doctrine\Common\DataFixtures\Executor\ORMExecutor($app['orm.em'], $purger);
        $executor->execute($loader->getFixtures());
    }

    register_shutdown_function(
        function ($app) {
            $path = $app['orm.default_cache']['path'];

            if (is_dir($path) === true) {
                $files = new \RecursiveIteratorIterator(
                    new \RecursiveDirectoryIterator($path),
                    \RecursiveIteratorIterator::CHILD_FIRST
                );

                foreach ($files as $file) {
                    if (in_array($file->getBasename(), array('.', '..')) !== true) {
                        if ($file->isDir() === true) {
                            rmdir($file->getPathName());
                        } elseif (($file->isFile() === true) || ($file->isLink() === true)) {
                            unlink($file->getPathname());
                        }
                    }
                }

                rmdir($path);
            } elseif ((is_file($path) === true) || (is_link($path) === true)) {
                return unlink($path);
            }
        },
        $app
    );
}
}

0 个答案:

没有答案