SlideShare a Scribd company logo
1 of 17
Download to read offline
Unit testing symfony plugins with PHPUnit


             Christian Schäfer
Christian Schäfer: Unit testing von symfony plugins with PHPUnit



About myself
●
    nick: caefer
●
    34, married, two cats
●
    senior system architect at Gruner+Jahr in hamburg
●
    web developer for over 11 years
●
    symfony developer for over 3 years


●
    blogs daily on http://test.ical.ly
●
    tweets @testically
●
    experiments on github.com/caefer
●
    loves scottish whisky, british comedy and uncommon music
    and his wife and two cats obviously :)
Christian Schäfer: Unit testing von symfony plugins with PHPUnit



What is your motivation?


• What is your main interest when developing plugins?
• Do you unit test your plugins?
• Who has worked with PHPUnit before?
Christian Schäfer: Unit testing von symfony plugins with PHPUnit



Defining the goals
When developing plugins you want to make sure they..


         • ..can be used stand-alone
         • ..can be installed easily
         • ..hold as little dependencies as possible*


         • ..work!




 *   where dependencies to symfony itself and Doctrine or Propel are only natural
Christian Schäfer: Unit testing von symfony plugins with PHPUnit



Prerequisites
In this talk I will be using the following:


       • symfony 1.4
       • PHPUnit 3.5
       • Hudson CI
       • sfTaskExtraPlugin


Always use sfTaskExtraPlugin when creating a new plugin!
Christian Schäfer: Unit testing von symfony plugins with PHPUnit



A word about unit testing in symfony 1
lime works! ..but
      • Not too well documented
      • Not found outside symfony
      • Not easy to integrate in continuous integration servers


 Why I prefer PHPUnit instead
      • It's well documented
      • It's well distributed
      • It's the de factor standard in the PHP world
      • It's actively maintained
      • It can easily be integrated in Hudson, phpUnderControl,
        Bamboo, yourFavouriteCISoftware
Christian Schäfer: Unit testing von symfony plugins with PHPUnit



Getting started
Did I mention to use sfTaskExtraPlugin ?



Create a plugin with this command:


     $ php symfony generate:plugin csTicTacToePlugin


Then take a look at the files that were created.
Two things are of particular interest:


       • test/fixtures/project/*
       • test/bootstrap/unit.php
Christian Schäfer: Unit testing von symfony plugins with PHPUnit



The fixture project
 The fixture project is a sandbox, a testing environment for your plugin.


• It is a fully working symfony project.
• You can even point a vHost to its web folder! (don't!)


• You can run symfony commands in it.*


• Add/remove/modify anything in it that your plugin requires of any
  project!
• Document everything you change.


 * beforehand: $ export SYMFONY=/path/to/your/symfony/lib/dir
Christian Schäfer: Unit testing von symfony plugins with PHPUnit



The fixture project - todos
• Configure a database connection


      dsn: sqlite::memory:


• Generate your models


      $ php symfony doctrine:build ­­all­classes


• Enable modules if exist
• Create test fixtures in data/fixtures/
• Create local schema.yml if required for testing (i.e. for behaviours)
• Enable plugins if required by your plugin
Christian Schäfer: Unit testing von symfony plugins with PHPUnit



The bootstrap
The bootstrapping process is responsible for firing up symfony and
all that is required for your tests.


This can include


      • Autoloading symfony
      • Enable required plugins (i.e. your own)
      • Autoloading project specific classes (i.e. model classes)
      • Database configuration
      • Rest of the configuration cascade
Christian Schäfer: Unit testing von symfony plugins with PHPUnit



The bootstrap - todos
• Remove lime

 require_once $configuration­>getSymfonyLibDir().'/vendor/lime/lime.php';



• Adjust project configuration to your needs

 $projectPath = dirname(__FILE__).'/../fixtures/project';
 1. Generic project config → symfony paths, plugins, project autoloading, database, configuration cascade
 $configuration = new sfProjectConfiguration($projectPath);
 2. Fixture project config → symfony paths, plugins, project autoloading, database, configuration cascade
 require_once($projectPath.'/config/ProjectConfiguration.class.php');
 $configuration = new ProjectConfiguration($projectPath);
 3. Fixture application config → symfony paths, plugins, project autoloading, database, configuration cascade
 require_once($projectPath.'/config/ProjectConfiguration.class.php');
 $configuration = ProjectConfiguration::getApplicationConfiguration('frontend', 'test', true);
Christian Schäfer: Unit testing von symfony plugins with PHPUnit



Pre-configuring PHPUnit
With the 3.5 release using PHPUnit became much more convenient!


Create a phpunit.xml.dist for a default configuration and ship it
with your plugin. Users can create their own phpunit.xml which will
be prefered by PHPUnit if it exists.


      • 1. Configure bootstrap
      • 2. Configure the path to the symfony lib dir
      • 3. Configure the path to the unit tests
      • 4. Configure scope for the coverage report
Christian Schäfer: Unit testing von symfony plugins with PHPUnit



Pre-configuring PHPUnit - todos
1. Configure bootstrap
<phpunit … bootstrap="test/bootstrap/unit.php" … >
2. Configure the path to the symfony lib dir
  <php><server name="SYMFONY" value="../symfony/"/></php>
3. Configure the path to the unit tests
  <testsuites>
    <testsuite name="csTicTacToePlugin Suite">
      <directory>./test/unit/</directory>
    </testsuite>
  </testsuites>
4. Configure scope for the coverage report
  <filter>
    <whitelist addUncoveredFilesFromWhitelist="true">
      <directory suffix=".php">./lib/</directory>
      <directory suffix=".php">./config/</directory>
    </whitelist>
  </filter>
Christian Schäfer: Unit testing von symfony plugins with PHPUnit



Using the database
 Always initialize the database in your TestCases setUp() method!*


• Initialize the database manager
 new sfDatabaseManager(ProjectConfiguration::getActive());
• Create database
 Doctrine_Manager::getInstance()­>createDatabases('doctrine');
• Create all tables
 Doctrine_Core::createTablesFromModels(sfConfig::get('sf_lib_dir'));
• Create specific tables
 Doctrine_Core::createTablesFromArray(array('SomeRecord', ..));
• Load fixtures
 Doctrine_Core::loadData(sfConfig::get('sf_data_dir').'/fixtures/fixtures.
 yml')


 * This is Doctrine specific! Unfortunately I don't know how to do the following with Propel..
Christian Schäfer: Unit testing von symfony plugins with PHPUnit



Lets see an example
Here's a simple plugin for demonstration:
http://github.com/caefer/csTicTacToePlugin


Here are a few of my best practices:
      • Test every class in your config and lib folder.
      • Write one test case per class.
      • Mirror the directory structure in your test/unit folder.
      • Name you test case like the covered class postfixed with “Test”.


    config/csTicTacToePluginConfiguration.class.php
    lib/model/doctrine/PluginTicTacToe.class.php
    → test/unit/config/csTicTacToePluginConfiguration.class.php
    → test/unit/lib/model/doctrine/PluginTicTacToe.class.php
Christian Schäfer: Unit testing von symfony plugins with PHPUnit




      Questions anybody?
Christian Schäfer: Unit testing von symfony plugins with PHPUnit




             Cheers!
      ..now let's go to lunch.

More Related Content

What's hot

Automation testing with Drupal 8
Automation testing with Drupal 8Automation testing with Drupal 8
Automation testing with Drupal 8nagpalprachi
 
Subversion @ JUG Milano 11 dic 2009
Subversion @ JUG Milano 11 dic 2009Subversion @ JUG Milano 11 dic 2009
Subversion @ JUG Milano 11 dic 2009Andrea Francia
 
Building and deploying PHP applications with Phing
Building and deploying PHP applications with PhingBuilding and deploying PHP applications with Phing
Building and deploying PHP applications with PhingMichiel Rook
 
Write book in markdown
Write book in markdownWrite book in markdown
Write book in markdownLarry Cai
 
Host any project in che with stacks & chefiles
Host any project in che with stacks & chefilesHost any project in che with stacks & chefiles
Host any project in che with stacks & chefilesFlorent BENOIT
 
Virtual Bolt Workshop - March 16, 2020
Virtual Bolt Workshop - March 16, 2020Virtual Bolt Workshop - March 16, 2020
Virtual Bolt Workshop - March 16, 2020Puppet
 
Learning Puppet Chapter 1
Learning Puppet Chapter 1Learning Puppet Chapter 1
Learning Puppet Chapter 1Vishal Biyani
 
Symfony Under Control by Maxim Romanovsky
Symfony Under Control by Maxim RomanovskySymfony Under Control by Maxim Romanovsky
Symfony Under Control by Maxim Romanovskyphp-user-group-minsk
 
Virtual Bolt Workshop - 6 May
Virtual Bolt Workshop - 6 MayVirtual Bolt Workshop - 6 May
Virtual Bolt Workshop - 6 MayPuppet
 
Deploying Symfony | symfony.cat
Deploying Symfony | symfony.catDeploying Symfony | symfony.cat
Deploying Symfony | symfony.catPablo Godel
 
Creating your own AtoM demo data set for re-use with Vagrant
Creating your own AtoM demo data set for re-use with VagrantCreating your own AtoM demo data set for re-use with Vagrant
Creating your own AtoM demo data set for re-use with VagrantArtefactual Systems - AtoM
 
Vagrant move over, here is Docker
Vagrant move over, here is DockerVagrant move over, here is Docker
Vagrant move over, here is DockerNick Belhomme
 
Python Flask app deployed to OPenShift using Wercker CI
Python Flask app deployed to OPenShift using Wercker CIPython Flask app deployed to OPenShift using Wercker CI
Python Flask app deployed to OPenShift using Wercker CIBruno Rocha
 
Practical PHP Deployment with Jenkins
Practical PHP Deployment with JenkinsPractical PHP Deployment with Jenkins
Practical PHP Deployment with JenkinsAdam Culp
 
GateKeeper - bypass or not bypass?
GateKeeper - bypass or not bypass?GateKeeper - bypass or not bypass?
GateKeeper - bypass or not bypass?Csaba Fitzl
 

What's hot (20)

Creating custom themes in AtoM
Creating custom themes in AtoMCreating custom themes in AtoM
Creating custom themes in AtoM
 
Nginx pres
Nginx presNginx pres
Nginx pres
 
Automation testing with Drupal 8
Automation testing with Drupal 8Automation testing with Drupal 8
Automation testing with Drupal 8
 
Subversion @ JUG Milano 11 dic 2009
Subversion @ JUG Milano 11 dic 2009Subversion @ JUG Milano 11 dic 2009
Subversion @ JUG Milano 11 dic 2009
 
Building and deploying PHP applications with Phing
Building and deploying PHP applications with PhingBuilding and deploying PHP applications with Phing
Building and deploying PHP applications with Phing
 
Write book in markdown
Write book in markdownWrite book in markdown
Write book in markdown
 
Host any project in che with stacks & chefiles
Host any project in che with stacks & chefilesHost any project in che with stacks & chefiles
Host any project in che with stacks & chefiles
 
Virtual Bolt Workshop - March 16, 2020
Virtual Bolt Workshop - March 16, 2020Virtual Bolt Workshop - March 16, 2020
Virtual Bolt Workshop - March 16, 2020
 
Learning Puppet Chapter 1
Learning Puppet Chapter 1Learning Puppet Chapter 1
Learning Puppet Chapter 1
 
Symfony Under Control by Maxim Romanovsky
Symfony Under Control by Maxim RomanovskySymfony Under Control by Maxim Romanovsky
Symfony Under Control by Maxim Romanovsky
 
Virtual Bolt Workshop - 6 May
Virtual Bolt Workshop - 6 MayVirtual Bolt Workshop - 6 May
Virtual Bolt Workshop - 6 May
 
Deploying Symfony | symfony.cat
Deploying Symfony | symfony.catDeploying Symfony | symfony.cat
Deploying Symfony | symfony.cat
 
Creating your own AtoM demo data set for re-use with Vagrant
Creating your own AtoM demo data set for re-use with VagrantCreating your own AtoM demo data set for re-use with Vagrant
Creating your own AtoM demo data set for re-use with Vagrant
 
Vagrant move over, here is Docker
Vagrant move over, here is DockerVagrant move over, here is Docker
Vagrant move over, here is Docker
 
Power Shell For Testers
Power Shell For TestersPower Shell For Testers
Power Shell For Testers
 
Python Flask app deployed to OPenShift using Wercker CI
Python Flask app deployed to OPenShift using Wercker CIPython Flask app deployed to OPenShift using Wercker CI
Python Flask app deployed to OPenShift using Wercker CI
 
Installing AtoM with Ansible
Installing AtoM with AnsibleInstalling AtoM with Ansible
Installing AtoM with Ansible
 
Practical PHP Deployment with Jenkins
Practical PHP Deployment with JenkinsPractical PHP Deployment with Jenkins
Practical PHP Deployment with Jenkins
 
GateKeeper - bypass or not bypass?
GateKeeper - bypass or not bypass?GateKeeper - bypass or not bypass?
GateKeeper - bypass or not bypass?
 
Pycon 2008: Python Command-line Tools *Nix
Pycon 2008:  Python Command-line Tools *NixPycon 2008:  Python Command-line Tools *Nix
Pycon 2008: Python Command-line Tools *Nix
 

Viewers also liked

lipolyse laser ou mincir sans effort
lipolyse laser ou mincir sans effort lipolyse laser ou mincir sans effort
lipolyse laser ou mincir sans effort aesthelys
 
Biological Solutions in a chemical world
Biological Solutions in a chemical worldBiological Solutions in a chemical world
Biological Solutions in a chemical worldThomas Schäfer
 
Designing Collaboration: Building Systems that Really Work - Philipp Schäfer
Designing Collaboration: Building Systems that Really Work - Philipp SchäferDesigning Collaboration: Building Systems that Really Work - Philipp Schäfer
Designing Collaboration: Building Systems that Really Work - Philipp SchäferOpenKnowledge srl
 
UNIVERSITY PORTFOLIO - ERIN SCHAFER
UNIVERSITY PORTFOLIO - ERIN SCHAFER UNIVERSITY PORTFOLIO - ERIN SCHAFER
UNIVERSITY PORTFOLIO - ERIN SCHAFER Erin Schafer
 
E-COMMERCE E AUTOMAZIONE: LE SMART SOLUTIONS DI SSI SCHÄFER
E-COMMERCE E AUTOMAZIONE: LE SMART SOLUTIONS DI SSI SCHÄFERE-COMMERCE E AUTOMAZIONE: LE SMART SOLUTIONS DI SSI SCHÄFER
E-COMMERCE E AUTOMAZIONE: LE SMART SOLUTIONS DI SSI SCHÄFERlogisticaefficiente
 
FSLN: Interaktive lernressourcen Abschlusspräsentation
FSLN: Interaktive lernressourcen AbschlusspräsentationFSLN: Interaktive lernressourcen Abschlusspräsentation
FSLN: Interaktive lernressourcen AbschlusspräsentationAlexander Schäfer
 
Social Business und eRecruiting_IBM Symposium2013_Kay Buck
Social Business und eRecruiting_IBM Symposium2013_Kay BuckSocial Business und eRecruiting_IBM Symposium2013_Kay Buck
Social Business und eRecruiting_IBM Symposium2013_Kay BuckIBM Switzerland
 
Presentation ibm pascal gaussen à la fevad mars2012
Presentation ibm pascal gaussen à la fevad mars2012Presentation ibm pascal gaussen à la fevad mars2012
Presentation ibm pascal gaussen à la fevad mars2012Henri Kaufman
 
Schafer Corporation
Schafer CorporationSchafer Corporation
Schafer CorporationJoseph Brown
 
Cours bota 2012 - niveau débutant
Cours bota 2012 - niveau débutantCours bota 2012 - niveau débutant
Cours bota 2012 - niveau débutantaudreytocco
 
Cours bota 2012 - niveau intermédiaire
Cours bota 2012 - niveau intermédiaireCours bota 2012 - niveau intermédiaire
Cours bota 2012 - niveau intermédiaireaudreytocco
 
IoT vs. Industrie Vergleich
IoT vs. Industrie VergleichIoT vs. Industrie Vergleich
IoT vs. Industrie VergleichPlamen Kiradjiev
 
Fonctions Mono-Ligne
Fonctions Mono-LigneFonctions Mono-Ligne
Fonctions Mono-Lignewebreaker
 
Manipulation des Données , cours sql oracle
Manipulation des Données , cours sql oracleManipulation des Données , cours sql oracle
Manipulation des Données , cours sql oraclewebreaker
 
Mise en Forme des Résultats avec SQL*Plus
Mise en Forme des Résultats avec SQL*PlusMise en Forme des Résultats avec SQL*Plus
Mise en Forme des Résultats avec SQL*Pluswebreaker
 
Conférence en ligne LinkedIn - Recruter à l'ère du mobile
Conférence en ligne LinkedIn - Recruter à l'ère du mobileConférence en ligne LinkedIn - Recruter à l'ère du mobile
Conférence en ligne LinkedIn - Recruter à l'ère du mobileLinkedIn
 
WHAT DO YOU STAND FOR? - COOLBRANDS PEOPLE
WHAT DO YOU STAND FOR? - COOLBRANDS PEOPLEWHAT DO YOU STAND FOR? - COOLBRANDS PEOPLE
WHAT DO YOU STAND FOR? - COOLBRANDS PEOPLECoolBrands People
 

Viewers also liked (20)

lipolyse laser ou mincir sans effort
lipolyse laser ou mincir sans effort lipolyse laser ou mincir sans effort
lipolyse laser ou mincir sans effort
 
Biological Solutions in a chemical world
Biological Solutions in a chemical worldBiological Solutions in a chemical world
Biological Solutions in a chemical world
 
Designing Collaboration: Building Systems that Really Work - Philipp Schäfer
Designing Collaboration: Building Systems that Really Work - Philipp SchäferDesigning Collaboration: Building Systems that Really Work - Philipp Schäfer
Designing Collaboration: Building Systems that Really Work - Philipp Schäfer
 
UNIVERSITY PORTFOLIO - ERIN SCHAFER
UNIVERSITY PORTFOLIO - ERIN SCHAFER UNIVERSITY PORTFOLIO - ERIN SCHAFER
UNIVERSITY PORTFOLIO - ERIN SCHAFER
 
E-COMMERCE E AUTOMAZIONE: LE SMART SOLUTIONS DI SSI SCHÄFER
E-COMMERCE E AUTOMAZIONE: LE SMART SOLUTIONS DI SSI SCHÄFERE-COMMERCE E AUTOMAZIONE: LE SMART SOLUTIONS DI SSI SCHÄFER
E-COMMERCE E AUTOMAZIONE: LE SMART SOLUTIONS DI SSI SCHÄFER
 
FSLN: Interaktive lernressourcen Abschlusspräsentation
FSLN: Interaktive lernressourcen AbschlusspräsentationFSLN: Interaktive lernressourcen Abschlusspräsentation
FSLN: Interaktive lernressourcen Abschlusspräsentation
 
Coordinated assessment
Coordinated assessmentCoordinated assessment
Coordinated assessment
 
Social Business und eRecruiting_IBM Symposium2013_Kay Buck
Social Business und eRecruiting_IBM Symposium2013_Kay BuckSocial Business und eRecruiting_IBM Symposium2013_Kay Buck
Social Business und eRecruiting_IBM Symposium2013_Kay Buck
 
Presentation ibm pascal gaussen à la fevad mars2012
Presentation ibm pascal gaussen à la fevad mars2012Presentation ibm pascal gaussen à la fevad mars2012
Presentation ibm pascal gaussen à la fevad mars2012
 
Schafer Corporation
Schafer CorporationSchafer Corporation
Schafer Corporation
 
La Petite Histoire Des Subprimes
La Petite Histoire Des SubprimesLa Petite Histoire Des Subprimes
La Petite Histoire Des Subprimes
 
Cours bota 2012 - niveau débutant
Cours bota 2012 - niveau débutantCours bota 2012 - niveau débutant
Cours bota 2012 - niveau débutant
 
Cours bota 2012 - niveau intermédiaire
Cours bota 2012 - niveau intermédiaireCours bota 2012 - niveau intermédiaire
Cours bota 2012 - niveau intermédiaire
 
IoT vs. Industrie Vergleich
IoT vs. Industrie VergleichIoT vs. Industrie Vergleich
IoT vs. Industrie Vergleich
 
Fonctions Mono-Ligne
Fonctions Mono-LigneFonctions Mono-Ligne
Fonctions Mono-Ligne
 
Manipulation des Données , cours sql oracle
Manipulation des Données , cours sql oracleManipulation des Données , cours sql oracle
Manipulation des Données , cours sql oracle
 
Mise en Forme des Résultats avec SQL*Plus
Mise en Forme des Résultats avec SQL*PlusMise en Forme des Résultats avec SQL*Plus
Mise en Forme des Résultats avec SQL*Plus
 
Conférence en ligne LinkedIn - Recruter à l'ère du mobile
Conférence en ligne LinkedIn - Recruter à l'ère du mobileConférence en ligne LinkedIn - Recruter à l'ère du mobile
Conférence en ligne LinkedIn - Recruter à l'ère du mobile
 
WHAT DO YOU STAND FOR? - COOLBRANDS PEOPLE
WHAT DO YOU STAND FOR? - COOLBRANDS PEOPLEWHAT DO YOU STAND FOR? - COOLBRANDS PEOPLE
WHAT DO YOU STAND FOR? - COOLBRANDS PEOPLE
 
Hr innovation day 2015
Hr innovation day 2015Hr innovation day 2015
Hr innovation day 2015
 

Similar to Unit testing symfony plugins with php unit

Nashville Php Symfony Presentation
Nashville Php Symfony PresentationNashville Php Symfony Presentation
Nashville Php Symfony PresentationBrent Shaffer
 
Automated testing with Drupal
Automated testing with DrupalAutomated testing with Drupal
Automated testing with DrupalPromet Source
 
Fabien Potencier "Symfony 4 in action"
Fabien Potencier "Symfony 4 in action"Fabien Potencier "Symfony 4 in action"
Fabien Potencier "Symfony 4 in action"Fwdays
 
Build & deploy PHP application (intro level)
Build & deploy PHP application (intro level)Build & deploy PHP application (intro level)
Build & deploy PHP application (intro level)Anton Babenko
 
Symfony Components 2.0 on PHP 5.3
Symfony Components 2.0 on PHP 5.3Symfony Components 2.0 on PHP 5.3
Symfony Components 2.0 on PHP 5.3Fabien Potencier
 
Effizientere WordPress-Plugin-Entwicklung mit Softwaretests
Effizientere WordPress-Plugin-Entwicklung mit SoftwaretestsEffizientere WordPress-Plugin-Entwicklung mit Softwaretests
Effizientere WordPress-Plugin-Entwicklung mit SoftwaretestsDECK36
 
Productivity 101: Making a Easily Re-deployable Dev Environment with Subversion
Productivity 101: Making a Easily Re-deployable Dev Environment with SubversionProductivity 101: Making a Easily Re-deployable Dev Environment with Subversion
Productivity 101: Making a Easily Re-deployable Dev Environment with Subversionryanduff
 
Introduce fuego
Introduce fuegoIntroduce fuego
Introduce fuegos60030
 
Test automation with php codeception
Test automation with php codeceptionTest automation with php codeception
Test automation with php codeceptionbuddhieash
 
Symfony4 - Deep dive
Symfony4 - Deep diveSymfony4 - Deep dive
Symfony4 - Deep diveSalma Ghareeb
 
Testing mit Codeception: Full-stack testing PHP framework
Testing mit Codeception: Full-stack testing PHP frameworkTesting mit Codeception: Full-stack testing PHP framework
Testing mit Codeception: Full-stack testing PHP frameworkSusannSgorzaly
 
Symfony 4: A new way to develop applications #ipc19
Symfony 4: A new way to develop applications #ipc19Symfony 4: A new way to develop applications #ipc19
Symfony 4: A new way to develop applications #ipc19Antonio Peric-Mazar
 
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)Fabrice Bernhard
 
Extracting twitter data using apache flume
Extracting twitter data using apache flumeExtracting twitter data using apache flume
Extracting twitter data using apache flumeBharat Khanna
 
Hands-on with the Symfony2 Framework
Hands-on with the Symfony2 FrameworkHands-on with the Symfony2 Framework
Hands-on with the Symfony2 FrameworkRyan Weaver
 
Symfony 4: A new way to develop applications #phpsrb
 Symfony 4: A new way to develop applications #phpsrb Symfony 4: A new way to develop applications #phpsrb
Symfony 4: A new way to develop applications #phpsrbAntonio Peric-Mazar
 
One commit, one release. Continuously delivering a Symfony project.
One commit, one release. Continuously delivering a Symfony project.One commit, one release. Continuously delivering a Symfony project.
One commit, one release. Continuously delivering a Symfony project.Javier López
 

Similar to Unit testing symfony plugins with php unit (20)

Nashville Php Symfony Presentation
Nashville Php Symfony PresentationNashville Php Symfony Presentation
Nashville Php Symfony Presentation
 
Automated testing with Drupal
Automated testing with DrupalAutomated testing with Drupal
Automated testing with Drupal
 
Fabien Potencier "Symfony 4 in action"
Fabien Potencier "Symfony 4 in action"Fabien Potencier "Symfony 4 in action"
Fabien Potencier "Symfony 4 in action"
 
Build & deploy PHP application (intro level)
Build & deploy PHP application (intro level)Build & deploy PHP application (intro level)
Build & deploy PHP application (intro level)
 
Symfony Components 2.0 on PHP 5.3
Symfony Components 2.0 on PHP 5.3Symfony Components 2.0 on PHP 5.3
Symfony Components 2.0 on PHP 5.3
 
Effizientere WordPress-Plugin-Entwicklung mit Softwaretests
Effizientere WordPress-Plugin-Entwicklung mit SoftwaretestsEffizientere WordPress-Plugin-Entwicklung mit Softwaretests
Effizientere WordPress-Plugin-Entwicklung mit Softwaretests
 
Productivity 101: Making a Easily Re-deployable Dev Environment with Subversion
Productivity 101: Making a Easily Re-deployable Dev Environment with SubversionProductivity 101: Making a Easily Re-deployable Dev Environment with Subversion
Productivity 101: Making a Easily Re-deployable Dev Environment with Subversion
 
Introduce fuego
Introduce fuegoIntroduce fuego
Introduce fuego
 
Test automation with php codeception
Test automation with php codeceptionTest automation with php codeception
Test automation with php codeception
 
Symfony4 - Deep dive
Symfony4 - Deep diveSymfony4 - Deep dive
Symfony4 - Deep dive
 
Continuous feature-development
Continuous feature-developmentContinuous feature-development
Continuous feature-development
 
Testing mit Codeception: Full-stack testing PHP framework
Testing mit Codeception: Full-stack testing PHP frameworkTesting mit Codeception: Full-stack testing PHP framework
Testing mit Codeception: Full-stack testing PHP framework
 
Symfony 4: A new way to develop applications #ipc19
Symfony 4: A new way to develop applications #ipc19Symfony 4: A new way to develop applications #ipc19
Symfony 4: A new way to develop applications #ipc19
 
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)
 
Extracting twitter data using apache flume
Extracting twitter data using apache flumeExtracting twitter data using apache flume
Extracting twitter data using apache flume
 
Hands-on with the Symfony2 Framework
Hands-on with the Symfony2 FrameworkHands-on with the Symfony2 Framework
Hands-on with the Symfony2 Framework
 
Running Symfony
Running SymfonyRunning Symfony
Running Symfony
 
Symfony 4: A new way to develop applications #phpsrb
 Symfony 4: A new way to develop applications #phpsrb Symfony 4: A new way to develop applications #phpsrb
Symfony 4: A new way to develop applications #phpsrb
 
Symfony 2.0 on PHP 5.3
Symfony 2.0 on PHP 5.3Symfony 2.0 on PHP 5.3
Symfony 2.0 on PHP 5.3
 
One commit, one release. Continuously delivering a Symfony project.
One commit, one release. Continuously delivering a Symfony project.One commit, one release. Continuously delivering a Symfony project.
One commit, one release. Continuously delivering a Symfony project.
 

Recently uploaded

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 

Recently uploaded (20)

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 

Unit testing symfony plugins with php unit

  • 1. Unit testing symfony plugins with PHPUnit Christian Schäfer
  • 2. Christian Schäfer: Unit testing von symfony plugins with PHPUnit About myself ● nick: caefer ● 34, married, two cats ● senior system architect at Gruner+Jahr in hamburg ● web developer for over 11 years ● symfony developer for over 3 years ● blogs daily on http://test.ical.ly ● tweets @testically ● experiments on github.com/caefer ● loves scottish whisky, british comedy and uncommon music and his wife and two cats obviously :)
  • 3. Christian Schäfer: Unit testing von symfony plugins with PHPUnit What is your motivation? • What is your main interest when developing plugins? • Do you unit test your plugins? • Who has worked with PHPUnit before?
  • 4. Christian Schäfer: Unit testing von symfony plugins with PHPUnit Defining the goals When developing plugins you want to make sure they.. • ..can be used stand-alone • ..can be installed easily • ..hold as little dependencies as possible* • ..work! * where dependencies to symfony itself and Doctrine or Propel are only natural
  • 5. Christian Schäfer: Unit testing von symfony plugins with PHPUnit Prerequisites In this talk I will be using the following: • symfony 1.4 • PHPUnit 3.5 • Hudson CI • sfTaskExtraPlugin Always use sfTaskExtraPlugin when creating a new plugin!
  • 6. Christian Schäfer: Unit testing von symfony plugins with PHPUnit A word about unit testing in symfony 1 lime works! ..but • Not too well documented • Not found outside symfony • Not easy to integrate in continuous integration servers Why I prefer PHPUnit instead • It's well documented • It's well distributed • It's the de factor standard in the PHP world • It's actively maintained • It can easily be integrated in Hudson, phpUnderControl, Bamboo, yourFavouriteCISoftware
  • 7. Christian Schäfer: Unit testing von symfony plugins with PHPUnit Getting started Did I mention to use sfTaskExtraPlugin ? Create a plugin with this command: $ php symfony generate:plugin csTicTacToePlugin Then take a look at the files that were created. Two things are of particular interest: • test/fixtures/project/* • test/bootstrap/unit.php
  • 8. Christian Schäfer: Unit testing von symfony plugins with PHPUnit The fixture project The fixture project is a sandbox, a testing environment for your plugin. • It is a fully working symfony project. • You can even point a vHost to its web folder! (don't!) • You can run symfony commands in it.* • Add/remove/modify anything in it that your plugin requires of any project! • Document everything you change. * beforehand: $ export SYMFONY=/path/to/your/symfony/lib/dir
  • 9. Christian Schäfer: Unit testing von symfony plugins with PHPUnit The fixture project - todos • Configure a database connection dsn: sqlite::memory: • Generate your models $ php symfony doctrine:build ­­all­classes • Enable modules if exist • Create test fixtures in data/fixtures/ • Create local schema.yml if required for testing (i.e. for behaviours) • Enable plugins if required by your plugin
  • 10. Christian Schäfer: Unit testing von symfony plugins with PHPUnit The bootstrap The bootstrapping process is responsible for firing up symfony and all that is required for your tests. This can include • Autoloading symfony • Enable required plugins (i.e. your own) • Autoloading project specific classes (i.e. model classes) • Database configuration • Rest of the configuration cascade
  • 11. Christian Schäfer: Unit testing von symfony plugins with PHPUnit The bootstrap - todos • Remove lime require_once $configuration­>getSymfonyLibDir().'/vendor/lime/lime.php'; • Adjust project configuration to your needs $projectPath = dirname(__FILE__).'/../fixtures/project'; 1. Generic project config → symfony paths, plugins, project autoloading, database, configuration cascade $configuration = new sfProjectConfiguration($projectPath); 2. Fixture project config → symfony paths, plugins, project autoloading, database, configuration cascade require_once($projectPath.'/config/ProjectConfiguration.class.php'); $configuration = new ProjectConfiguration($projectPath); 3. Fixture application config → symfony paths, plugins, project autoloading, database, configuration cascade require_once($projectPath.'/config/ProjectConfiguration.class.php'); $configuration = ProjectConfiguration::getApplicationConfiguration('frontend', 'test', true);
  • 12. Christian Schäfer: Unit testing von symfony plugins with PHPUnit Pre-configuring PHPUnit With the 3.5 release using PHPUnit became much more convenient! Create a phpunit.xml.dist for a default configuration and ship it with your plugin. Users can create their own phpunit.xml which will be prefered by PHPUnit if it exists. • 1. Configure bootstrap • 2. Configure the path to the symfony lib dir • 3. Configure the path to the unit tests • 4. Configure scope for the coverage report
  • 13. Christian Schäfer: Unit testing von symfony plugins with PHPUnit Pre-configuring PHPUnit - todos 1. Configure bootstrap <phpunit … bootstrap="test/bootstrap/unit.php" … > 2. Configure the path to the symfony lib dir   <php><server name="SYMFONY" value="../symfony/"/></php> 3. Configure the path to the unit tests   <testsuites>     <testsuite name="csTicTacToePlugin Suite">       <directory>./test/unit/</directory>     </testsuite>   </testsuites> 4. Configure scope for the coverage report   <filter>     <whitelist addUncoveredFilesFromWhitelist="true">       <directory suffix=".php">./lib/</directory>       <directory suffix=".php">./config/</directory>     </whitelist>   </filter>
  • 14. Christian Schäfer: Unit testing von symfony plugins with PHPUnit Using the database Always initialize the database in your TestCases setUp() method!* • Initialize the database manager new sfDatabaseManager(ProjectConfiguration::getActive()); • Create database Doctrine_Manager::getInstance()­>createDatabases('doctrine'); • Create all tables Doctrine_Core::createTablesFromModels(sfConfig::get('sf_lib_dir')); • Create specific tables Doctrine_Core::createTablesFromArray(array('SomeRecord', ..)); • Load fixtures Doctrine_Core::loadData(sfConfig::get('sf_data_dir').'/fixtures/fixtures. yml') * This is Doctrine specific! Unfortunately I don't know how to do the following with Propel..
  • 15. Christian Schäfer: Unit testing von symfony plugins with PHPUnit Lets see an example Here's a simple plugin for demonstration: http://github.com/caefer/csTicTacToePlugin Here are a few of my best practices: • Test every class in your config and lib folder. • Write one test case per class. • Mirror the directory structure in your test/unit folder. • Name you test case like the covered class postfixed with “Test”. config/csTicTacToePluginConfiguration.class.php lib/model/doctrine/PluginTicTacToe.class.php → test/unit/config/csTicTacToePluginConfiguration.class.php → test/unit/lib/model/doctrine/PluginTicTacToe.class.php
  • 16. Christian Schäfer: Unit testing von symfony plugins with PHPUnit Questions anybody?
  • 17. Christian Schäfer: Unit testing von symfony plugins with PHPUnit Cheers! ..now let's go to lunch.