{"id":1921,"date":"2016-03-11T14:35:20","date_gmt":"2016-03-11T14:35:20","guid":{"rendered":"https:\/\/intelligentbee.com\/blog\/?p=1921"},"modified":"2024-11-28T13:53:52","modified_gmt":"2024-11-28T13:53:52","slug":"setup-testing-and-fixtures-in-symfony2-the-easy-way","status":"publish","type":"post","link":"https:\/\/intelligentbee.com\/blog\/setup-testing-and-fixtures-in-symfony2-the-easy-way\/","title":{"rendered":"Setup Testing and Fixtures in Symfony2: The Easy Way"},"content":{"rendered":"<p>Setting up testing and fixtures in Symfony2 is vital if you plan on starting Test Driven Development or you simply want to start covering your code with properly written tests that can access mock data.<\/p>\n<p>&nbsp;<\/p>\n<h2>1.\u00a0Install PHPUnit and php 5.6<\/h2>\n<p>The first thing you need to do is to install <span style=\"color: #ff6600;\"><a style=\"color: #ff6600;\" title=\"PHPUnit\" href=\"https:\/\/phpunit.de\/\" target=\"_blank\" rel=\"noopener\">PHPUnit<\/a><\/span> on your machine:<\/p>\n<pre class=\"toolbar:2 marking:false nums:false nums-toggle:false wrap-toggle:false whitespace-before:1 whitespace-after:1 lang:apache decode:true\">$ wget https:\/\/phar.phpunit.de\/phpunit.phar\r\n$ chmod +x phpunit.phar\r\n$ sudo mv phpunit.phar \/usr\/local\/bin\/phpunit\r\n$ phpunit --version<\/pre>\n<p>and then, if needed, also upgrade your PHP version to 5.6:<\/p>\n<pre class=\"toolbar:2 marking:false nums:false nums-toggle:false wrap-toggle:false whitespace-before:1 whitespace-after:1 lang:apache decode:true \">$ sudo apt-get install language-pack-en-base\r\n$ export LC_CTYPE=\"en_US.UTF-8\"\r\n$ sudo add-apt-repository ppa:ondrej\/php5-5.6\r\n$ sudo apt-get update\r\n$ sudo apt-get install php5<\/pre>\n<p>and make sure everything&#8217;s ok by running: <code>phpunit -c app\/<\/code><\/p>\n<p>Please note that this is not a testing tutorial so if you&#8217;d like to learn more about how to actually test your Symfony2 app, then please <span style=\"color: #ff6600;\"><a style=\"color: #ff6600;\" title=\"Testing in Symfony\" href=\"http:\/\/symfony.com\/doc\/current\/book\/testing.html\" target=\"_blank\" rel=\"noopener\">read their documentation<\/a><\/span>.<\/p>\n<p>&nbsp;<\/p>\n<h3>2. Setup and create a test database<\/h3>\n<p>In order to be able to configure testing and fixtures in a Symfony2 app a separate, independent database is needed so that your dev environment is not affected.<\/p>\n<p>In the <code>config_test.yml<\/code> file you simply need to add:<\/p>\n<pre class=\"toolbar:2 marking:false nums:false nums-toggle:false wrap-toggle:false whitespace-before:1 whitespace-after:1 lang:yaml decode:true \">doctrine:\r\n    dbal:\r\n        host:     127.0.0.1\r\n        dbname:   testdb\r\n        user:     [YOUR_MYSQL_USERNAME]\r\n        password:  [YOUR_MYSQL_PASSWORD]<\/pre>\n<p>then simply run <code>php app\/console doctrine:database:create --env=test<\/code><\/p>\n<p>&nbsp;<\/p>\n<p><span style=\"color: #ff6600;\"><strong>Related<\/strong>:\u00a0<a style=\"color: #ff6600;\" title=\"Send Emails in Symfony2: The Right Way\" href=\"https:\/\/intelligentbee.com\/blog\/send-emails-in-symfony2-the-right-way\/\" target=\"_blank\" rel=\"noopener\">Send Emails in Symfony2: The Right Way<\/a><\/span><\/p>\n<p>&nbsp;<\/p>\n<h3>3. Build the BaseTestSetup class<\/h3>\n<p>Once our test database is ready\u00a0we can start building our <code>BaseTestSetup<\/code> class, one which will serve as parent for all of our tests.<\/p>\n<pre class=\"toolbar:2 marking:false nums:false nums-toggle:false wrap-toggle:false whitespace-before:1 whitespace-after:1 lang:php decode:true\">&lt;?php\r\nnamespace AppBundle\\Tests;\r\nuse Symfony\\Bundle\\FrameworkBundle\\Test\\WebTestCase;\r\n\r\nabstract class BaseTestSetup extends WebTestCase\r\n{\r\n    protected $client;\r\n    protected $container;\r\n    protected $em;\r\n\r\n    protected function setUp()\r\n    {\r\n        $this-&gt;client = static::createClient();\r\n        $this-&gt;container = $this-&gt;client-&gt;getContainer();\r\n        $this-&gt;em = static::$kernel-&gt;getContainer()\r\n            -&gt;get('doctrine')\r\n            -&gt;getManager();\r\n    }\r\n}<\/pre>\n<p>&nbsp;<\/p>\n<h3>4. Install the LiipFunctionalTestBundle<\/h3>\n<p>Even though Symfony does have an\u00a0out of the box solution\u00a0to setup and test your app, <span style=\"color: #ff6600;\"><a style=\"color: #ff6600;\" title=\"LiipFunctionalTestBundle\" href=\"https:\/\/github.com\/liip\/LiipFunctionalTestBundle\" target=\"_blank\" rel=\"noopener\">the LiipFunctionalTestBundle\u00a0provides base classes for functional tests to assist in setting up testing and\u00a0fixtures and HTML5 validation<\/a><\/span>.<\/p>\n<p>After you install and configure the bundle, go back to your <code>BaseTestSetup<\/code> class and make the necessary modifications:<\/p>\n<pre class=\"toolbar:2 marking:false nums:false nums-toggle:false wrap-toggle:false whitespace-before:1 whitespace-after:1 lang:php decode:true\">&lt;?php\r\nnamespace AppBundle\\Tests;\r\nuse Doctrine\\ORM\\Tools\\SchemaTool;\r\nuse Liip\\FunctionalTestBundle\\Test\\WebTestCase;\r\n\r\nabstract class BaseTestSetup extends WebTestCase\r\n{\r\n    protected $client;\r\n    protected $container;\r\n    protected $em;\r\n\r\n    protected function setUp()\r\n    {\r\n        $this-&gt;client = static::createClient();\r\n        $this-&gt;container = $this-&gt;client-&gt;getContainer();\r\n        $this-&gt;em = static::$kernel-&gt;getContainer()\r\n            -&gt;get('doctrine')\r\n            -&gt;getManager();\r\n        \r\n        if (!isset($metadatas)) {\r\n            $metadatas = $this-&gt;em-&gt;getMetadataFactory()-&gt;getAllMetadata();\r\n        }\r\n        $schemaTool = new SchemaTool($this-&gt;em);\r\n        $schemaTool-&gt;dropDatabase();\r\n        if (!empty($metadatas)) {\r\n            $schemaTool-&gt;createSchema($metadatas);\r\n        }\r\n        $this-&gt;postFixtureSetup();\r\n\r\n        $this-&gt;loadFixtures(array(\r\n            'AppBundle\\DataFixtures\\ORM\\LoadUserData',\r\n        ));\r\n\r\n    }\r\n}<\/pre>\n<p>The new code above simply drops and creates the database each them tests run. Then it loads the fixtures that you&#8217;ll need. The <code>LoadUserData<\/code> class does not exist yet so we&#8217;ll go right ahead and add it <span style=\"color: #ff6600;\"><a style=\"color: #ff6600;\" title=\"DoctrineFixturesBundle\" href=\"http:\/\/symfony.com\/doc\/current\/bundles\/DoctrineFixturesBundle\/index.html\" target=\"_blank\" rel=\"noopener\">by following the handy tutorial found on Symfony&#8217;s website<\/a><\/span>.<\/p>\n<p>&nbsp;<\/p>\n<h3>5. Write the very first test<\/h3>\n<p>Now that have your fixtures ready, you can go ahead and write your first test. Create a new file in your <code>AppBundle\/Tests<\/code> folder called <code>UserTest.php<\/code>, next to <code>BaseTestSetup.php<\/code>:<\/p>\n<pre class=\"toolbar:2 marking:false nums:false nums-toggle:false wrap-toggle:false whitespace-before:1 whitespace-after:1 lang:php decode:true \">&lt;?php\r\nnamespace AppBundle\\Tests;\r\n\r\nuse AppBundle\\Tests\\BaseTestSetup;\r\n\r\nclass UserTest extends BaseTestSetup \r\n{   \r\n    public function testSuggestImprovementEmail()\r\n    {   \r\n        \/\/ assuming that you named your user 'username' in your Fixtures\r\n        $crawler = $this-&gt;client-&gt;request('GET', '\/show\/username');\r\n\r\n        $this-&gt;assertGreaterThan(\r\n            0,\r\n            $crawler-&gt;filter('html:contains(\"Hello first user!\")')-&gt;count()\r\n        );\r\n    }\r\n\r\n}<\/pre>\n<p>&nbsp;<\/p>\n<p>And that&#8217;s about it! You\u00a0now have everything you need to properly test your awesome app.<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Setting up testing and fixtures in Symfony2 is vital if you plan on starting Test Driven Development or you simply [&hellip;]<\/p>\n","protected":false},"author":28,"featured_media":1945,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[82],"tags":[139,194,231,238],"yst_prominent_words":[273,394,528,530,977,990,1147,1398],"post_mailing_queue_ids":[],"_links":{"self":[{"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/posts\/1921"}],"collection":[{"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/users\/28"}],"replies":[{"embeddable":true,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/comments?post=1921"}],"version-history":[{"count":3,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/posts\/1921\/revisions"}],"predecessor-version":[{"id":133329,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/posts\/1921\/revisions\/133329"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/media\/1945"}],"wp:attachment":[{"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/media?parent=1921"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/categories?post=1921"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/tags?post=1921"},{"taxonomy":"yst_prominent_words","embeddable":true,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/yst_prominent_words?post=1921"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}