简体   繁体   English

Zend Framework 2如何对Doctrine 2实体进行单元测试

[英]Zend Framework 2 How To Unit Test Doctrine 2 Entities

So I am using Doctrine 2 module in Zend Framework. 所以我在Zend Framework中使用Doctrine 2模块。 I got everything working inside my controllers. 我把所有东西都放在了控制器里面。 I can do: 我可以:

use ModuleName\Entity\User;

And then in controller action: 然后在控制器动作中:

$user = new User;
$user->username = 'john.doe';
$user->password = md5('password');
$this->_getEntityManager()->persist($user);
$this->_getEntityManager()->flush();

And it's working correctly. 它工作正常。 A new row in the database is created. 创建数据库中的新行。

When I try the same thing inside my unit tests I get: 当我在单元测试中尝试相同的事情时,我得到:

class_parents(): Class User does not exist and could not be loaded
/Users/richardknop/Projects/myproject/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/RuntimeReflectionService.php:40
/Users/richardknop/Projects/myproject/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php:257

Any ideas? 有任何想法吗? I am using the same bootstrap for my unit tests as for my application. 我使用相同的引导程序进行单元测试,就像我的应用程序一样。 In unit tests I extend PHPUnit_Framework_TestCase. 在单元测试中,我扩展了PHPUnit_Framework_TestCase。

im bootsrappong my tests like this: 我喜欢这样的测试:

I have have the testsuite setup in module/Something/tests 我在module/Something/tests有testsuite设置

run-tests.php 运行tests.php

#!/usr/bin/env php
<?php

chdir(__DIR__);
$paths = array();
if ($argc > 1) {
    foreach ($argv as $key => $path) {

        if (!$key) continue;
        system('phpunit -c '. __DIR__ . DIRECTORY_SEPARATOR . 'phpunit.xml '. __DIR__ . DIRECTORY_SEPARATOR . $path, $result);
        echo $result;
    }

} else {

    system('phpunit -c '. __DIR__ . DIRECTORY_SEPARATOR . 'phpunit.xml '. __DIR__, $result);
    echo $result;
}

** phpunit.xml ** phpunit.xml

<phpunit
    bootstrap="./Bootstrap.php"
    backupGlobals="false"
    backupStaticAttributes="false"
    cacheTokens="true"
    colors="true"
    convertErrorsToExceptions="true"
    convertNoticesToExceptions="true"
    convertWarningsToExceptions="true"
    forceCoversAnnotation="false"
    mapTestClassNameToCoveredClassName="false"
    processIsolation="false"
    stopOnError="false"
    stopOnFailure="false"
    stopOnIncomplete="false"
    stopOnSkipped="false"
    strict="false"
    verbose="true"
>
    <testsuites>
        <testsuite name="Module Test Suite">
            <directory>./</directory>
        </testsuite>
    </testsuites>
</phpunit>

TestConfiguration.php TestConfiguration.php

<?php

return array(
    'output_buffering' => false, // required for testing sessions
    'modules' => array(
        //'DoctrineModule',
        //'DoctrineORMModule',
        'Base',
    ),
    'module_listener_options' => array(
        'config_glob_paths' => array(
            'config/autoload/{,*.}{global,local}.php',
        ),
        'module_paths' => array(
            './module',
            './vendor',
        ),
    ),
);

Boostrap.php Boostrap.php

<?php

use Zend\ServiceManager\ServiceManager;
use Zend\Mvc\MvcEvent;
use Zend\Mvc\Service\ServiceManagerConfig;
use BaseModuleTest\TestCase;

error_reporting( E_ALL | E_STRICT );
chdir(__DIR__);

$configuration = @include __DIR__ . '/TestConfiguration.php';
if (isset($configuration['output_buffering']) && $configuration['output_buffering']) {

    ob_start(); // required to test sessions
}

spl_autoload_register('loadTestClass', true, false);
function loadTestClass($classname) {

    $file = __DIR__ . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $classname) . '.php';
    if (is_file($file) && is_readable($file)) {

        require_once $file;
    }
}


$previousDir = '.';
while (!file_exists('config/application.config.php')) {
    $dir = dirname(getcwd());

    if ($previousDir === $dir) {
        throw new RuntimeException(
            'Unable to locate "config/application.config.php":'
                . ' is DoctrineORMModule in a sub-directory of your application skeleton?'
        );
    }

    $previousDir = $dir;
    chdir($dir);
}

/////////////////////////////////////////////////////////////

require './module/Base/src/functions.php';

if  (!@include_once 'vendor/autoload.php') {
    throw new RuntimeException('vendor/autoload.php could not be found. Did you run `php composer.phar install`?');
}

$serviceManager = new ServiceManager(new ServiceManagerConfig(
    isset($configuration['service_manager']) ? $configuration['service_manager'] : array()
));
$serviceManager->setService('ApplicationConfig', $configuration);
$serviceManager->setFactory('ServiceListener', 'Zend\Mvc\Service\ServiceListenerFactory');

/** @var $moduleManager \Zend\ModuleManager\ModuleManager */
$moduleManager = $serviceManager->get('ModuleManager');
$moduleManager->loadModules();
$serviceManager->setAllowOverride(true);

$application = $serviceManager->get('Application');
$event  = new MvcEvent();
$event->setTarget($application);
$event->setApplication($application)
    ->setRequest($application->getRequest())
    ->setResponse($application->getResponse())
    ->setRouter($serviceManager->get('Router'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Zend Framework 2:如何在phpunit的单元测试中包括Doctrine2支持? - Zend Framework 2: How to include Doctrine2 support in unit testing with phpunit? 使用准则2和Zend Framework 2,没有映射的ORM实体 - No mapped ORM entities, Using doctrine 2 and Zend Framework 2 从实体生成Zend Framework 2和Doctrine 2数据库 - Zend framework 2 and Doctrine 2 database generation from entities Zend Framework和Doctrine 2 - 我的单元测试是否足够? - Zend Framework and Doctrine 2 - are my unit tests sufficient? Zend Framework 2 - 如何对自己的会话服务进行单元测试? - Zend Framework 2 - how to unit test own session service? 在Zend Framework 2中生成具有多个数据库连接的Doctrine 2实体 - Generating Doctrine 2 entities with multiple database connections in Zend Framework 2 Zend框架单元测试在assertResponseCode(200)上失败 - Zend Framework Unit Test fails on assertResponseCode(200) Zend Framework中的单元测试json输出 - Unit Test json output in Zend Framework Zend Framework 2 Doctrine 2模块-控制器单元测试中没有服务定位器 - Zend Framework 2 Doctrine 2 Module - No Service Locator in Controller Unit Tests 如何在 Zend 框架 3(学说/迁移)中播种数据库? - How to seed database in zend framework 3 (doctrine/migrations)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM