You can find out how to install the part of the manual you need in the description of the repository by the link . (For example, if you want to start with this lesson without going through the previous one)
The board
If you plan to write your own Open Source Symfony2 bundles, you are much more likely to get a good response from users if your bundle is well tested (and documented). Look at the list of existing symfony2 bundles available on knpbundles .
// Check 1 === 1 is true $this->assertTrue(1 === 1); // Check 1 === 2 is false $this->assertFalse(1 === 2); // Check 'Hello' equals 'Hello' $this->assertEquals('Hello', 'Hello'); // Check array has key 'language' $this->assertArrayHasKey('language', array('language' => 'php', 'size' => '1024')); // Check array contains value 'php' $this->assertContains('php', array('php', 'ruby', 'c++', 'JavaScript'));
The board
If you are using VCS, such as Git, you must add the app / phpunit.xml file to the ignore list.
<!-- app/phpunit.xml --> <testsuites> <testsuite name="Project Test Suite"> <directory>../src/*/*Bundle/Tests</directory> <directory>../src/*/Bundle/*Bundle/Tests</directory> </testsuite> </testsuites>
The board
For more information on configuring PHPUnit using an XML file, see the PHPUnit documentation.
$ phpunit -c app
<?php namespace Blogger\BlogBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class DefaultControllerTest extends WebTestCase { public function testIndex() { $client = static::createClient(); $crawler = $client->request('GET', '/'); $this->assertContains('Hello World', $client->getResponse()->getContent()); } }
src/Blogger/BlogBundle/ Entity/ Blog.php Comment.php Controller/ PageController.php Twig/ Extensions/ BloggerBlogExtension.php Tests/ Entity/ BlogTest.php CommentTest.php Controller/ PageControllerTest.php Twig/ Extensions/ BloggerBlogExtensionTest.php
<?php // src/Blogger/BlogBundle/Tests/Entity/BlogTest.php namespace Blogger\BlogBundle\Tests\Entity; use Blogger\BlogBundle\Entity\Blog; class BlogTest extends \PHPUnit_Framework_TestCase { }
// src/Blogger/BlogBundle/Tests/Entity/BlogTest.php // .. class BlogTest extends \PHPUnit_Framework_TestCase { public function testSlugify() { $blog = new Blog(); $this->assertEquals('hello-world', $blog->slugify('Hello World')); } }
$ phpunit -c app
PHPUnit 5.4.6 by Sebastian Bergmann and contributors. . 1 / 1 (100%) Time: 348 ms, Memory: 13.25MB OK (1 test, 1 assertion)
// src/Blogger/BlogBundle/Tests/Entity/BlogTest.php // .. public function testSlugify() { $blog = new Blog(); $this->assertEquals('hello-world', $blog->slugify('Hello World')); $this->assertEquals('a day with symfony2', $blog->slugify('A Day With Symfony2')); }
PHPUnit 5.4.6 by Sebastian Bergmann and contributors. F 1 / 1 (100%) Time: 340 ms, Memory: 13.25MB There was 1 failure: 1) Blogger\BlogBundle\Tests\Entity\BlogTest::testSlugify Failed asserting that two strings are equal. --- Expected +++ Actual @@ @@ -'a day with symfony2' +'a-day-with-symfony2' D:\local\symfony-blog\src\Blogger\BlogBundle\Tests\Entity\BlogTest.php:15 FAILURES! Tests: 1, Assertions: 2, Failures: 1.
// src/Blogger/BlogBundle/Tests/Entity/BlogTest.php // .. public function testSlugify() { $blog = new Blog(); $this->assertEquals('hello-world', $blog->slugify('Hello World')); $this->assertEquals('a-day-with-symfony2', $blog->slugify('A Day With Symfony2')); }
// src/Blogger/BlogBundle/Tests/Entity/BlogTest.php // .. public function testSlugify() { $blog = new Blog(); $this->assertEquals('hello-world', $blog->slugify('Hello World')); $this->assertEquals('a-day-with-symfony2', $blog->slugify('A Day With Symfony2')); $this->assertEquals('hello-world', $blog->slugify('Hello world')); $this->assertEquals('symblog', $blog->slugify('symblog ')); $this->assertEquals('symblog', $blog->slugify(' symblog')); }
// src/Blogger/BlogBundle/Tests/Entity/BlogTest.php // .. public function testSetSlug() { $blog = new Blog(); $blog->setSlug('Symfony2 Blog'); $this->assertEquals('symfony2-blog', $blog->getSlug()); } public function testSetTitle() { $blog = new Blog(); $blog->setTitle('Hello World'); $this->assertEquals('hello-world', $blog->getSlug()); }
<?php // src/Blogger/BlogBundle/Tests/Twig/Extensions/BloggerBlogExtensionTest.php namespace Blogger\BlogBundle\Tests\Twig\Extensions; use Blogger\BlogBundle\Twig\Extensions\BloggerBlogExtension; class BloggerBlogExtensionTest extends \PHPUnit_Framework_TestCase { public function testCreatedAgo() { $blog = new BloggerBlogExtension(); $this->assertEquals("0 seconds ago", $blog->createdAgo(new \DateTime())); $this->assertEquals("34 seconds ago", $blog->createdAgo($this->getDateTime(-34))); $this->assertEquals("1 minute ago", $blog->createdAgo($this->getDateTime(-60))); $this->assertEquals("2 minutes ago", $blog->createdAgo($this->getDateTime(-120))); $this->assertEquals("1 hour ago", $blog->createdAgo($this->getDateTime(-3600))); $this->assertEquals("1 hour ago", $blog->createdAgo($this->getDateTime(-3601))); $this->assertEquals("2 hours ago", $blog->createdAgo($this->getDateTime(-7200))); // Cannot create time in the future $this->setExpectedException('\InvalidArgumentException'); $blog->createdAgo($this->getDateTime(60)); } protected function getDateTime($delta) { return new \DateTime(date("Ymd H:i:s", time()+$delta)); } }
$ phpunit -c app src/Blogger/BlogBundle/Tests/Twig/Extensions/BloggerBlogExtensionTest.php
1) Blogger\BlogBundle\Tests\Twig\Extensions\BloggerBlogExtensionTest::testCreatedAgo Failed asserting that two strings are equal. --- Expected +++ Actual @@ @@ -'0 seconds ago' +'0 second ago' //..
<?php // src/Blogger/BlogBundle/Twig/Extensions/BloggerBlogBundle.php namespace Blogger\BlogBundle\Twig\Extensions; class BloggerBlogExtension extends \Twig_Extension { // .. public function createdAgo(\DateTime $dateTime) { // .. if ($delta < 60) { // Seconds $time = $delta; $duration = $time . " second" . (($time === 0 || $time > 1) ? "s" : "") . " ago"; } // .. } // .. }
1) Blogger\BlogBundle\Tests\Twig\Extensions\BloggerBlogExtensionTest::testCreatedAgo Failed asserting that two strings are equal. --- Expected +++ Actual @@ @@ -'1 hour ago' +'60 minutes ago'
<?php // src/Blogger/BlogBundle/Twig/Extensions/BloggerBlogBundle.php namespace Blogger\BlogBundle\Twig\Extensions; class BloggerBlogExtension extends \Twig_Extension { // .. public function createdAgo(\DateTime $dateTime) { // .. else if ($delta < 3600) { // Mins $time = floor($delta / 60); $duration = $time . " minute" . (($time > 1) ? "s" : "") . " ago"; } else if ($delta < 86400) { // Hours $time = floor($delta / 3600); $duration = $time . " hour" . (($time > 1) ? "s" : "") . " ago"; } // .. } // .. }
$ phpunit -c app
The board
Try adding your own unit tests.
<?php // src/Blogger/BlogBundle/Tests/Controller/PageControllerTest.php namespace Blogger\BlogBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class PageControllerTest extends WebTestCase { public function testAbout() { $client = static::createClient(); $crawler = $client->request('GET', '/about'); $this->assertEquals(1, $crawler->filter('h1:contains("About symblog")')->count()); } }
// vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Test/WebTestCase.php abstract class WebTestCase extends KernelTestCase { // .. }
$ phpunit -c app/ src/Blogger/BlogBundle/Tests/Controller/PageControllerTest.php
// src/Blogger/BlogBundle/Tests/Controller/PageControllerTest.php public function testIndex() { $client = static::createClient(); $crawler = $client->request('GET', '/'); // Check there are some blog entries on the page $this->assertTrue($crawler->filter('article.blog')->count() > 0); }
$ phpunit -c app/ src/Blogger/BlogBundle/Tests/Controller/PageControllerTest.php
<article class="blog"> <div class="date"><time datetime="2016-06-17T14:23:55+03:00">Friday, June 17, 2016</time></div> <header> <h2><a href="/1/a-day-with-symfony2">A day with Symfony2</a></h2> </header> //.. </article>
$ phpunit -c app/ src/Blogger/BlogBundle/Tests/Controller/PageControllerTest.php
// src/Blogger/BlogBundle/Tests/Controller/PageControllerTest.php public function testContact() { $client = static::createClient(); $crawler = $client->request('GET', '/contact'); $this->assertEquals(1, $crawler->filter('h1:contains("Contact symblog")')->count()); // Select based on button value, or id or name for buttons $form = $crawler->selectButton('Submit')->form(); $form['contact[name]'] = 'name'; $form['contact[email]'] = 'email@email.com'; $form['contact[subject]'] = 'Subject'; $form['contact[body]'] = 'The comment body must be at least 50 characters long as there is a validation constrain on the Enquiry entity'; $crawler = $client->submit($form); $this->assertEquals(1, $crawler->filter('.blogger-notice:contains("Your contact enquiry was successfully sent. Thank you!")')->count()); }
$ phpunit -c app/ src/Blogger/BlogBundle/Tests/Controller/PageControllerTest.php
1) Blogger\BlogBundle\Tests\Controller\PageControllerTest::testContact Failed asserting that 0 matches expected 1. D:\local\symfony-blog\src\Blogger\BlogBundle\Tests\Controller\PageControllerTest.php:55 FAILURES! Tests: 3, Assertions: 5, Failures: 1.
// src/Blogger/BlogBundle/Tests/Controller/PageControllerTest.php public function testContact() { // .. $crawler = $client->submit($form); // Need to follow redirect $crawler = $client->followRedirect(); $this->assertEquals(1, $crawler->filter('.blogger-notice:contains("Your contact enquiry was successfully sent. Thank you!")')->count()); }
# app/config/config_test.yml swiftmailer: disable_delivery: true
// src/Blogger/BlogBundle/Tests/Controller/PageControllerTest.php public function testContact() { // .. $crawler = $client->submit($form); // Check email has been sent if ($profile = $client->getProfile()) { $swiftMailerProfiler = $profile->getCollector('swiftmailer'); // Only 1 message should have been sent $this->assertEquals(1, $swiftMailerProfiler->getMessageCount()); // Get the first message $messages = $swiftMailerProfiler->getMessages(); $message = array_shift($messages); $symblogEmail = $client->getContainer()->getParameter('blogger_blog.emails.contact_email'); // Check message is being sent to correct address $this->assertArrayHasKey($symblogEmail, $message->getTo()); } // Need to follow redirect $crawler = $client->followRedirect(); $this->assertTrue($crawler->filter('.blogger-notice:contains("Your contact enquiry was successfully sent. Thank you!")')->count() > 0); }
, , , , .
$ phpunit -c app/ src/Blogger/BlogBundle/Tests/Controller/PageControllerTest.php
<?php // src/Blogger/BlogBundle/Tests/Controller/BlogControllerTest.php namespace Blogger\BlogBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class BlogControllerTest extends WebTestCase { public function testAddBlogComment() { $client = static::createClient(); $crawler = $client->request('GET', '/1/a-day-with-symfony'); $this->assertEquals(1, $crawler->filter('h2:contains("A day with Symfony2")')->count()); // Select based on button value, or id or name for buttons $form = $crawler->selectButton('Submit')->form(); $crawler = $client->submit($form, array( 'blogger_blogbundle_commenttype[user]' => 'name', 'blogger_blogbundle_commenttype[comment]' => 'comment', )); // Need to follow redirect $crawler = $client->followRedirect(); // Check comment is now displaying on page, as the last entry. This ensure comments // are posted in order of oldest to newest $articleCrawler = $crawler->filter('section .previous-comments article')->last(); $this->assertEquals('name', $articleCrawler->filter('header span.highlight')->text()); $this->assertEquals('comment', $articleCrawler->filter('p')->last()->text()); // Check the sidebar to ensure latest comments are display and there is 10 of them $this->assertEquals(10, $crawler->filter('aside.sidebar section')->last() ->filter('article')->count() ); $this->assertEquals('name', $crawler->filter('aside.sidebar section')->last() ->filter('article')->first() ->filter('header span.highlight')->text() ); } }
$ phpunit -c app/ src/Blogger/BlogBundle/Tests/Controller/BlogControllerTest.php
Tip
We could also use an object-oriented interface to set form field values. Examples are shown below.
// Tick a checkbox $form['show_emal']->tick(); // Select an option or a radio $form['gender']->select('Male');
<?php // src/Blogger/BlogBundle/Tests/Repository/BlogRepositoryTest.php namespace Blogger\BlogBundle\Tests\Repository; use Blogger\BlogBundle\Entity\Repository\BlogRepository; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class BlogRepositoryTest extends WebTestCase { /** * @var \Blogger\BlogBundle\Entity\Repository\BlogRepository */ private $blogRepository; public function setUp() { $kernel = static::createKernel(); $kernel->boot(); $this->blogRepository = $kernel->getContainer() ->get('doctrine.orm.entity_manager') ->getRepository('BloggerBlogBundle:Blog'); } public function testGetTags() { $tags = $this->blogRepository->getTags(); $this->assertTrue(count($tags) > 1); $this->assertContains('symblog', $tags); } public function testGetTagWeights() { $tagsWeight = $this->blogRepository->getTagWeights( array('php', 'code', 'code', 'symblog', 'blog') ); $this->assertTrue(count($tagsWeight) > 1); // Test case where count is over max weight of 5 $tagsWeight = $this->blogRepository->getTagWeights( array_fill(0, 10, 'php') ); $this->assertTrue(count($tagsWeight) >= 1); // Test case with multiple counts over max weight of 5 $tagsWeight = $this->blogRepository->getTagWeights( array_merge(array_fill(0, 10, 'php'), array_fill(0, 2, 'html'), array_fill(0, 6, 'js')) ); $this->assertEquals(5, $tagsWeight['php']); $this->assertEquals(3, $tagsWeight['js']); $this->assertEquals(1, $tagsWeight['html']); // Test empty case $tagsWeight = $this->blogRepository->getTagWeights(array()); $this->assertEmpty($tagsWeight); } }
$ phpunit -c app/ src/Blogger/BlogBundle/Tests/Repository/BlogRepositoryTest.php
$ phpunit --coverage-html ./phpunit-report -c app/
, , , .
1 — Symfony2
2 — : ,
3 — Doctrine 2
4 — , Doctrine 2
5 — Twig , (sidebar) Assetic
Source: https://habr.com/ru/post/303578/
All Articles