cosma / testing-bundle
测试包
Requires
- php: >=5.3.3
- doctrine/orm: ~2.2,>=2.2.3
- facebook/webdriver: 1.1.*
- h4cc/alice-fixtures-bundle: 0.5.*
- mockery/mockery: 0.9.*
- phpunit/phpunit: 4.*
- predis/predis: 1.0.*
- ruflin/elastica: 3.*
- solarium/solarium: 3.4.*
- symfony/framework-bundle: 2.8.*
Requires (Dev)
- symfony/browser-kit: 2.8.*
This package is not auto-updated.
Last update: 2024-09-28 17:43:39 UTC
README
是h4cc/AliceFixturesBundle的扩展,一个用于灵活使用nelmio/alice fixtures的Symfony2包,与非常强大的数据生成器fzaninotto/Faker集成。此包还集成了mockery/mockery库。Testing Bundle包使用.yml格式的数据固定,与常见的Doctrine DataFixtures分离。有多种方式来加载固定文件。Testing Bundle提供从.yml加载固定文件,删除并重新创建ORM Schema。
目录
安装
$ php composer.phar require cosma/testing-bundle '2.0.*'
关注'dev-master'分支以获取最新开发版本。但如果可能,我建议使用更稳定的版本标签。
之后,将h4ccAliceFixturesBundle和TestingBundle添加到您的Kernel中,最有可能是在"dev"或"test"环境中。
# app/AppKernel.php <?php public function registerBundles() { $bundles = array( // ... ); if (in_array($this->getEnvironment(), array('dev', 'test'))) { // ... $bundles[] = new h4cc\AliceFixturesBundle\h4ccAliceFixturesBundle(); $bundles[] = new Cosma\Bundle\TestingBundle\TestingBundle(); } }
配置
如果您想更改固定目录的默认路径,可以配置testing bundle的fixture_path。这将设置一个新相对路径到固定目录在您的包中。
# app/config/config_test.yml cosma_testing: fixture_directory: Fixture tests_directory: Tests doctrine: cleaning_strategy: truncate # drop - to drop database solarium: host: 127.0.0.1 port: 8080 path: /solr core: test timeout: 10 elastica: host: 127.0.0.1 port: 9200 path: / timeout: 10 index: test selenium: remote_server_url: http://127.0.0.1:4444/wd/hub test_domain: example.com redis: scheme: tcp host: 127.0.0.1 port: 6379 database: 13 timeout: 5
生成测试类
使用命令cosma_testing:generate:test,您可以从PHP文件生成类和特质的存根测试类。
# Argument :: file - required
$ php app/console cosma_testing:generate:test /path/to/file/containing/classes_or_traits.php
测试用例
支持以下测试用例
简单测试用例
此用例是PHPUnit_Framework_TestCase的扩展,有两个额外简单的方法
- getMockedEntityWithId ($entity, $id)
- getEntityWithId ($entity, $id)
- getTestClassPath ()
use Cosma\Bundle\TestingBundle\TestCase\SimpleTestCase; class SomeVerySimpleUnitTest extends SimpleTestCase { public function testSomething() { $mockedUserFullNamespace = $this->getMockedEntityWithId('Acme\AppBundle\Entity\User', 1); $mockedUserBundleNamespace = $this->getMockedEntityWithId('AppBundle:User', 2); $userFullNamespace = $this->getEntityWithId('Acme\AppBundle\Entity\User', 3); $userBundleNamespace = $this->getEntityWithId('AppBundle:User', 4); $thisTestClassPath = $this->getTestClassPath(); } }
Web测试用例
此用例是Symfony2 WebTestCase的扩展 - Symfony\Bundle\FrameworkBundle\Test\WebTestCase,具有以下方法
- getKernel ()
- getContainer ()
- getClient (array $server)
use Cosma\Bundle\TestingBundle\TestCase\WebTestCase; class SomeWebFunctionalTest extends WebTestCase { public function setUp() { /** * Required call that boots the Symfony kernel */ parent::setUp(); } public function testSomething() { $kernel = $this->getKernel(); $container = $this->getContainer(); // Client for functional tests. Emulates a browser $client = $this->getClient(); } }
DB测试用例
此用例是带有数据库和固定支持的Symfony WebTestCase的扩展
具有以下方法
- dropDatabase ()
- loadFixtures (array $fixtures, $dropDatabaseBefore = true)
- getEntityManager ()
- getEntityRepository ($entity)
- getFixtureManager ()
use Cosma\Bundle\TestingBundle\TestCase\DBTestCase; class SomeFunctionalWebDBTest extends WebTestCase { public function setUp() { /** * Required call that boots the Symfony kernel */ parent::setUp(); /** * drops database tables before every test. * has two strategies set by parameter cosma_testing.doctrine.cleaning_strategy: * 1. truncate (default, faster) * 2. drop (actual drop, slower) */ $this->dropDatabase(); /** * 1. Truncates the tables user and group(default behaviour) * 2. Loads two fixtures files located in src/AppBundle/Fixture/Table/User.yml and src/AnotherBundle/Fixture/Table/Group.yml * */ $this->loadFixtures( [ 'AppBundle:Table:User', 'AnotherBundle:Table:Group' ] ); /** * Loads a fixtures file located in src/SomeBundle/Fixture/SomeDirectory/Book.yml * Doesn't truncate the table */ $this->loadFixtures( [ 'SomeBundle:SomeDirectory:Book' ], false ); } public function testSomething() { /** * Fixtures can be load inside a test, too. */ $this->loadFixtures(['SomeBundle:SomeDirectory:Author']); $entityManager = $this->getEntityManager(); $entityRepository = $this->getEntityRepository('AppBundle:User'); $fixtureManager = $this->getFixtureManager(); } }
Solr测试用例
此用例是具有额外Solr支持的WebTestCase的扩展,来自当前包,具有以下方法
- getSolariumClient ()
use Cosma\Bundle\TestingBundle\TestCase\SolrTestCase; class SomeSolrTest extends SolrTestCase { public function setUp() { /** * Required call that boots the Symfony kernel and truncate default test Solr core */ parent::setUp(); } public function testIndex() { $solariumClient = $this->getSolariumClient(); /** * get an update query instance */ $update = $solariumClient->createUpdate(); /** * first fixture document */ $documentOne = $update->createDocument(); $documentOne->id = 123; $documentOne->name = 'testdoc-1'; $documentOne->price = 364; /** * second fixture document */ $documentTwo = $update->createDocument(); $documentTwo->id = 124; $documentTwo->name = 'testdoc-2'; $documentTwo->price = 340; /** * add the documents and a commit command to the update query */ $update->addDocuments([$documentOne, $documentTwo]); $update->addCommit(); /** * execute query */ $solariumClient->update($update); } }
Elastic Search测试用例
此用例是具有额外ElasticSearch支持的WebTestCase的扩展,来自当前包,具有以下方法
- getElasticIndex ()
- getElasticClient ()
class SomeElasticTest extends ElasticTestCase { public function setUp() { /** * Required call that boots the Symfony kernel and recreates default test elastic index */ parent::setUp(); } public function testSomethingElastic() { // get default Elastica client $elasticClient = $this->getElasticClient(); // get default index - test $elasticIndex = $this->getElasticIndex(); // create another index $anotherElasticIndex = $elasticClient->getIndex('another_index'); $anotherElasticIndex->create([], true); //Create a type /** @type \Elastica\Type $type **/ $type = $this->getElasticIndex()->getType('type'); // index documents $type->addDocument( new \Elastica\Document(1, ['username' => 'someUser']) ); $type->addDocument( new \Elastica\Document(2, ['username' => 'anotherUser']) ); $type->addDocument( new \Elastica\Document(3, ['username' => 'someotherUser']) ); $elasticIndex->refresh(); //query for documents $query = array( 'query' => array( 'query_string' => array( 'query' => '*User', ) ) ); $path = $elasticIndex->getName() . '/' . $type->getName() . '/_search'; $response = $elasticClient->request($path, Request::GET, $query); $responseArray = $response->getData(); $this->assertEquals(3, $responseArray['hits']['total']); } }
Selenium测试用例
此用例是带有额外Selenium支持的WebTestCase的扩展,具有以下方法
- getRemoteWebDriver ()
- getTestDomain ()
- open ($url)
- openSecure ($url)
use Cosma\Bundle\TestingBundle\TestCase\SeleniumTestCase; class SomeSeleniumTest extends SeleniumTestCase { public function setUp() { /** * Required call that boots the Symfony kernel and initialize selenium remote web driver */ parent::setUp(); } /** * read title from google site */ public function testGoogleTitle() { $remoteWebDriver = $this->getRemoteWebDriver(); $domain = $this->getTestDomain(); // open http url http://testdomain/somepage.html $webDriver = $this->open('/somepage.html'); $this->assertContains('Some Title', $webDriver->getTitle()); // open https url https://testdomain/securePage.html $webDriver = $this->openSecure('/securePage.html'); $this->assertContains('Some Title', $webDriver->getTitle()); } }
Redis测试用例
此用例是带有额外Redis支持的WebTestCase的扩展,具有以下方法
- getRedisClient ()
use Cosma\Bundle\TestingBundle\TestCase\RedisTestCase; class SomeSeleniumTest extends RedisTestCase { public function setUp() { /** * Required call that boots the Symfony kernel and initialize selenium remote web driver */ parent::setUp(); } /** * read title from google site */ public function testGoogleTitle() { $redisClient = $this->getRedisClient(); $redisClient->set('key' , 'value'); } }
组合测试用例
您可以使用以下在\Cosma\Bundle\TestingBundle\TestCase\Traits下定义的特质构建组合测试用例:支持以下测试用例
- SimpleTrait
- DBTrait
- CommandTrait
- ElasticTrait
- SolrTrait
- SeleniumTrait
- RedisTrait
所有组合测试用例都可以使用一个或多个特质并扩展Cosma\Bundle\TestingBundle\TestCase\WebTestCase
namespace Acme\AppBundle\TestCase; use Cosma\Bundle\TestingBundle\TestCase\WebTestCase; // add the rest of traits use Cosma\Bundle\TestingBundle\TestCase\Traits\DBTrait; use Cosma\Bundle\TestingBundle\TestCase\Traits\ElasticTrait; use Cosma\Bundle\TestingBundle\TestCase\Traits\SeleniumTrait; use Cosma\Bundle\TestingBundle\TestCase\Traits\RedisTrait; abstract class ComposedTestCase extends WebTestCase { /** * This Test Case combines: DB, Elastic and Selenium Test Cases */ use DBTrait; use ElasticTrait; use SeleniumTrait; use RedisTrait; public function setUp() { parent::setUp(); $this->getFixtureManager(); // from DBTrait $this->recreateIndex(); // from ElasticTrait $this->getRemoteWebDriver(); // from SeleniumTrait $this->resetRedisDatabase(); // from RedisTrait } }
重试测试
使用@retry注解对类或方法进行失败重试。方法注解会覆盖类注解。
use Cosma\Bundle\TestingBundle\TestCase\SimpleTestCase; /** * Will retry 10 times all the Class tests that are failing * * @retry 10 */ class SomeVerySimpleUnitTest extends SimpleTestCase { /** * Will retry 10 times this test if is failing because of the class annotation from above */ public function testFirst() { // ... } /** * Will retry 4 times this test if is failing because of the method annotation from below * * @retry 4 */ public function testSecond() { // ... } }
固定
Alice 最基本的功能是将扁平的YAML文件转换为对象。
您可以在一个文件中定义许多不同类的对象,如下所示
Nelmio\Entity\User: user{1..10}: username: <username()> fullname: <firstName()> <lastName()> birthDate: <date()> email: <email()> favoriteNumber: <numberBetween(1, 200)> Nelmio\Entity\Group: group1: name: Admins users: [@user1, @user4, @user7]
导入/导出模拟数据文件
您可以使用cosma_testing:fixtures:dump命令轻松将数据库数据导出到YAML模拟数据文件。
# Argument :: dump directory - required # Argument :: entity - if not specified will save all entities : default * # Option :: --associations / -a - saves the associations between entities, too $ php app/console cosma_testing:fixtures:export [-a|--associations] dumpDirectory [entity] $ php app/console cosma_testing:fixtures:export -a "path/to/dump/directory" BundleName:Entity
您可以使用h4cc_alice_fixtures:load:files命令轻松将YAML模拟数据文件导入到数据库。
# Argument :: list of files to import : required # Option :: --type / - t : Type of loader. Can be "yaml" or "php" : yaml default # Option :: --drop / -d : drop and create schema before loading # Option :: --no-persist / - np : persist loaded entities in database $ php app/console cosma_testing:fixtures:import [--drop] /path/to/fixtureFileOne.yml /path/to/fixtureFileTwo.yml
高级使用
为Faker添加自定义提供者
Faker的提供者可以是任何具有公共方法的类。这些方法可以在模拟数据文件中使用,用于自己的测试数据或计算。要注册提供者,创建一个服务并标记它。
示例
services: your.faker.provider: class: YourProviderClass tags: - { name: h4cc_alice_fixtures.provider }
为Alice添加自定义处理器
Alice处理器可以在持久化前后操纵对象。要注册自定义处理器,创建一个服务并标记它。
示例
services: your.alice.processor: class: YourProcessorClass tags: - { name: h4cc_alice_fixtures.processor }
Mockery
Mockery 是一个简单但灵活的PHP模拟对象框架,用于单元测试。
use Cosma\Bundle\TestingBundle\TestCase\SimpleTestCase; class SomeUnitTest extends SimpleTestCase { public function testGetsAverageTemperatureFromThreeServiceReadings() { $service = \Mockery::mock('service'); $service->shouldReceive('readTemp')->times(3)->andReturn(10, 12, 14); $temperature = new Temperature($service); $this->assertEquals(12, $temperature->average()); } }
运行测试
vendor/phpunit/phpunit/phpunit -c phpunit.xml.dist --coverage-text --coverage-html=Tests/coverage Tests
许可证
该捆绑包采用MIT许可。