SlideShare a Scribd company logo
August 25, 2014 
Tarun Kumar Singhal 
ZF2 PHPUnit
ZF2 PHPUnit 
Agenda 
What is PhpUnit 
Installation 
How to write an automated test 
Writing and running tests with PHPUnit 
Code-Coverage Analysis 
Advantages and disadvantages of PhpUnit
ZF2 PHPUnit 
Ballon Effect 
Testing your application what you build/changed. 
Retesting everything all the time is very important. 
That's take a lot of time.
ZF2 PHPUnit 
PhpUnit 
Testing with PHPUnit means checking that your 
program behaves as expected, and performing a 
battery of tests. 
These runnable code-fragments are called unit tests.
ZF2 PHPUnit 
Installation 
# pear config-set auto_discover 1 
# pear install pear.phpunit.de/PHPUnit 
// for code coverage 
# sudo pecl install xdebug
ZF2 PHPUnit 
Directory Tree 
Structure
ZF2 PHPUnit 
<?php 
return array( 
'modules' => array( 
TestConfig File 
//modules needed 
'User', 
'Products' 
), 
'module_listener_options' => array( 
'config_glob_paths' => array( 
'../../../config/autoload/{,*.}{global,local,message}.php', 
), 
'module_paths' => array( 
'module', 
'vendor', 
), 
), 
);
ZF2 PHPUnit 
PhpUnit XML File 
<?xml version="1.0" encoding="UTF-8"?> 
<phpunit bootstrap="Bootstrap.php"> 
<php> 
<server name="HTTP_HOST" value="http://irizf2.local.com" /> 
<server name="SERVER_PORT" value="80"/> 
<server name="REMOTE_ADDR" value=""/> 
<server name="PDO::MYSQL_ATTR_INIT_COMMAND" value="" /> 
</php> 
<testsuites> 
<testsuite name="Example Controller Tests"> 
<directory>./UserTest</directory> 
</testsuite> 
</testsuites> 
</phpunit>
ZF2 PHPUnit 
<?php 
namespace UserTest; // our namespace 
use ZendLoaderAutoloaderFactory; 
use ZendMvcServiceServiceManagerConfig; 
use ZendServiceManagerServiceManager; 
use ZendSessionContainer; 
use IridiumAcl; 
class Bootstrap 
{ 
public static function init() 
{ 
// Load the user-defined test configuration file, if it exists; otherwise, load 
if (is_readable(__DIR__ . '/TestConfig.php')) { 
$testConfig = include __DIR__ . '/TestConfig.php'; 
} else { 
$testConfig = include __DIR__ . '/TestConfig.php.dist'; 
} 
…........................ 
….......... 
Bootstrap File
ZF2 PHPUnit 
<?php 
namespace UserTestController; 
use ZendTestPHPUnitControllerAbstractHttpControllerTestCase; 
use ZendTestPHPUnitControllerAbstractControllerTestCase; 
class AdminControllerTest extends AbstractControllerTestCase 
{ 
protected $controller; 
protected $request; 
protected $response; 
protected $routeMatch; 
protected $event; 
protected $loginForm; 
protected $userMockObj; 
protected $callSummaryForm; 
protected $serviceManager; 
}
ZF2 PHPUnit 
public function setUp() 
{ 
$this->serviceManager = Bootstrap::getServiceManager(); 
$this->controller = new AdminController(); 
$this->request = new Request(); 
$tis->routeMatch = new RouteMatch(array('controller' => 'admin')); 
$this->event = new MvcEvent(); 
$config = $this->serviceManager->get('Config'); 
$routerConfig = isset($config['router']) ? $config['router'] : array(); 
$router = HttpRouter::factory($routerConfig); 
…............. 
…........ 
} 
PHPUnit supports sharing the setup code. Before a 
test method is run, a template method called setUp() is 
invoked. setUp() is where you create the objects 
against which you will test.
ZF2 PHPUnit 
Writing Tests with PHPUnit 
// To test the call-summary action 
public function testCallSummaryAction() 
{ 
$this->serviceManager->setAllowOverride(true); 
$this->serviceManager->setService('UserModelUserModel', $this->userMockObj); 
$this->routeMatch->setParam('action', 'call-summary'); 
$result = $this->controller->dispatch($this->request); 
$response = $this->controller->getResponse(); 
$this->assertEquals(200, $response->getStatusCode()); 
} 
//To test the delete-user action 
public function testDeleteUserAction() 
{ 
$this->routeMatch->setParam('action', 'delete-user'); 
$result = $this->controller->dispatch($this->request); 
$response = $this->controller->getResponse(); 
$this->assertEquals(302, $response->getStatusCode()); 
}
ZF2 PHPUnit 
Test class should extend the class 
AbstractControllerTestCase 
The tests are public methods that expect no parameters 
and are named test* 
Inside the test methods, assertion methods such as 
assertEquals() are used to assert that an actual value 
matches an expected value.
ZF2 PHPUnit 
The PHPUnit command-line test runner can be invoked through 
the phpunit command. 
# phpunit 
PHPUnit 4.1.3 by Sebastian Bergmann. 
.. 
Time: 00:00 
OK (2 tests) 
. Printed when the test succeeds. 
F Printed when an assertion fails while running the test method. 
E Printed when an error occurs while running the test method. 
S Printed when the test has been skipped. 
I Printed when the test is marked as being incomplete or not yet 
implemented.
ZF2 PHPUnit 
Incomplete Tests 
public function testSomething() 
{ 
// Stop here and mark this test as incomplete. 
$this->markTestIncomplete( 
'This test has not been implemented yet.‘); 
} 
A test as being marked as incomplete or not 
yet implemented.
ZF2 PHPUnit 
Fixtures 
setUp() method – is called before a test method run 
tearDown() method – is called after a test method run 
setUp() and tearDown() will be called once for each test 
method run.
ZF2 PHPUnit 
Code-Coverage Analysis 
How do you find code that is not yet tested? 
How do you measure testing completeness? 
#phpunit --coverage-html dir-name 
PHPUnit 4.1.3 by Sebastian Bergmann. 
.... 
Time: 00:00 
OK (4 tests) 
Generating report, this may take a moment.
ZF2 PHPUnit 
Classes
ZF2 PHPUnit
ZF2 PHPUnit 
Lines of code that were executed while running the tests are 
highlighted green, lines of code that are executable but were not 
executed are highlighted red, and "dead code" is highlighted gray.
ZF2 PHPUnit 
Advantages 
• Testing gives code authors and reviewers confidence 
that patches produce the correct results. 
• Detect errors just after code is written 
• The tests are run at the touch of a button and present 
their results in a clear format. 
• Tests run fast 
• The tests do not affect each other. If some changes 
are made in one test, the results of others tests do 
not change.
ZF2 PHPUnit 
Disadvantages 
Some people have trouble with getting started: 
where to put the files, how big the scope of one 
unit test is and when to write a separate testing 
suite and so on. 
It would be difficult to write a test for people who 
are not programmers or familiar with PHP.
ZF2 PHPUnit 
Thank You

More Related Content

What's hot (20)

PPT
Testing And Drupal
Peter Arato
 
PDF
Automated testing in Drupal
Artem Berdishev
 
PPT
How to test models using php unit testing framework?
satejsahu
 
PDF
PHP Unit Testing in Yii
IlPeach
 
PDF
Cursus phpunit
Nick Belhomme
 
PPTX
Codeception
少東 張
 
PDF
Testing PHP with Codeception
John Paul Ada
 
PPTX
PHPUnit with CakePHP and Yii
madhavi Ghadge
 
PDF
3 WAYS TO TEST YOUR COLDFUSION API
Gavin Pickin
 
PDF
TDD in Python With Pytest
Eddy Reyes
 
PDF
Acceptance testing in php with Codeception - Techmeetup Edinburgh
Engineor
 
PPT
JavaScript Unit Testing
Christian Johansen
 
PPT
JavaScript Unit Testing
Christian Johansen
 
PPT
Unit testing
Arthur Purnama
 
PDF
Testing with Codeception (Webelement #30)
Adam Štipák
 
PDF
prohuddle-utPLSQL v3 - Ultimate unit testing framework for Oracle
Jacek Gebal
 
ODP
Automated testing in Python and beyond
dn
 
PDF
Selenium interview questions and answers
kavinilavuG
 
PPT
Presentation_C++UnitTest
Raihan Masud
 
PDF
Automated Testing for Embedded Software in C or C++
Lars Thorup
 
Testing And Drupal
Peter Arato
 
Automated testing in Drupal
Artem Berdishev
 
How to test models using php unit testing framework?
satejsahu
 
PHP Unit Testing in Yii
IlPeach
 
Cursus phpunit
Nick Belhomme
 
Codeception
少東 張
 
Testing PHP with Codeception
John Paul Ada
 
PHPUnit with CakePHP and Yii
madhavi Ghadge
 
3 WAYS TO TEST YOUR COLDFUSION API
Gavin Pickin
 
TDD in Python With Pytest
Eddy Reyes
 
Acceptance testing in php with Codeception - Techmeetup Edinburgh
Engineor
 
JavaScript Unit Testing
Christian Johansen
 
JavaScript Unit Testing
Christian Johansen
 
Unit testing
Arthur Purnama
 
Testing with Codeception (Webelement #30)
Adam Štipák
 
prohuddle-utPLSQL v3 - Ultimate unit testing framework for Oracle
Jacek Gebal
 
Automated testing in Python and beyond
dn
 
Selenium interview questions and answers
kavinilavuG
 
Presentation_C++UnitTest
Raihan Masud
 
Automated Testing for Embedded Software in C or C++
Lars Thorup
 

Viewers also liked (18)

PDF
Zend Framework Estrutura e TDD
PHP Day Curitiba
 
PDF
Error Reporting in ZF2: form messages, custom error pages, logging
Steve Maraspin
 
PDF
Zend Framework и Doctrine
Stepan Tanasiychuk
 
PDF
Moduli su Zend Framework 2: come sfruttarli
Stefano Valle
 
PDF
Asset management with Zend Framework 2
Stefano Valle
 
PPS
Implementing access control with zend framework
George Mihailov
 
PDF
Instant ACLs with Zend Framework 2
Stefano Valle
 
PDF
Unit testing PHP apps with PHPUnit
Michelangelo van Dam
 
PDF
Into the ZF2 Service Manager
Chris Tankersley
 
PDF
Zend Framework 2 : Dependency Injection
Abdul Malik Ikhsan
 
PDF
PHPUnit best practices presentation
Thanh Robi
 
PDF
Clean Unit Test Patterns
Frank Appel
 
ODP
Creating fast, dynamic ACLs in Zend Framework (Zend Webinar)
Wim Godden
 
PPTX
Understanding Unit Testing
ikhwanhayat
 
PDF
Introduction to Unit Testing with PHPUnit
Michelangelo van Dam
 
PPTX
Unit Testing Concepts and Best Practices
Derek Smith
 
PPT
Zend Framework Workshop Parte2
massimiliano.wosz
 
PDF
GAME ON! Integrating Games and Simulations in the Classroom
Brian Housand
 
Zend Framework Estrutura e TDD
PHP Day Curitiba
 
Error Reporting in ZF2: form messages, custom error pages, logging
Steve Maraspin
 
Zend Framework и Doctrine
Stepan Tanasiychuk
 
Moduli su Zend Framework 2: come sfruttarli
Stefano Valle
 
Asset management with Zend Framework 2
Stefano Valle
 
Implementing access control with zend framework
George Mihailov
 
Instant ACLs with Zend Framework 2
Stefano Valle
 
Unit testing PHP apps with PHPUnit
Michelangelo van Dam
 
Into the ZF2 Service Manager
Chris Tankersley
 
Zend Framework 2 : Dependency Injection
Abdul Malik Ikhsan
 
PHPUnit best practices presentation
Thanh Robi
 
Clean Unit Test Patterns
Frank Appel
 
Creating fast, dynamic ACLs in Zend Framework (Zend Webinar)
Wim Godden
 
Understanding Unit Testing
ikhwanhayat
 
Introduction to Unit Testing with PHPUnit
Michelangelo van Dam
 
Unit Testing Concepts and Best Practices
Derek Smith
 
Zend Framework Workshop Parte2
massimiliano.wosz
 
GAME ON! Integrating Games and Simulations in the Classroom
Brian Housand
 
Ad

Similar to Zend Framework 2 - PHPUnit (20)

PPT
Phpunit
japan_works
 
PPT
Unit Testing using PHPUnit
varuntaliyan
 
PPTX
PHPUnit: from zero to hero
Jeremy Cook
 
KEY
Php Unit With Zend Framework Zendcon09
Michelangelo van Dam
 
PDF
Fighting Fear-Driven-Development With PHPUnit
James Fuller
 
PDF
2010 07-28-testing-zf-apps
Venkata Ramana
 
PPT
Test Driven Development with PHPUnit
Mindfire Solutions
 
PPTX
Test in action week 2
Yi-Huan Chan
 
PPTX
Unit Testng with PHP Unit - A Step by Step Training
Ram Awadh Prasad, PMP
 
PPT
Automated Unit Testing
Mike Lively
 
ZIP
Test
Eddie Kao
 
KEY
PHPUnit testing to Zend_Test
Michelangelo van Dam
 
KEY
Developer testing 101: Become a Testing Fanatic
LB Denker
 
KEY
Developer testing 201: When to Mock and When to Integrate
LB Denker
 
PDF
The state of PHPUnit
Edorian
 
PPT
PHPUnit Automated Unit Testing Framework
Dave Ross
 
PDF
13 PHPUnit #burningkeyboards
Denis Ristic
 
PDF
New Features PHPUnit 3.3 - Sebastian Bergmann
dpc
 
PDF
Unit testing in PHP
Lee Boynton
 
Phpunit
japan_works
 
Unit Testing using PHPUnit
varuntaliyan
 
PHPUnit: from zero to hero
Jeremy Cook
 
Php Unit With Zend Framework Zendcon09
Michelangelo van Dam
 
Fighting Fear-Driven-Development With PHPUnit
James Fuller
 
2010 07-28-testing-zf-apps
Venkata Ramana
 
Test Driven Development with PHPUnit
Mindfire Solutions
 
Test in action week 2
Yi-Huan Chan
 
Unit Testng with PHP Unit - A Step by Step Training
Ram Awadh Prasad, PMP
 
Automated Unit Testing
Mike Lively
 
Test
Eddie Kao
 
PHPUnit testing to Zend_Test
Michelangelo van Dam
 
Developer testing 101: Become a Testing Fanatic
LB Denker
 
Developer testing 201: When to Mock and When to Integrate
LB Denker
 
The state of PHPUnit
Edorian
 
PHPUnit Automated Unit Testing Framework
Dave Ross
 
13 PHPUnit #burningkeyboards
Denis Ristic
 
New Features PHPUnit 3.3 - Sebastian Bergmann
dpc
 
Unit testing in PHP
Lee Boynton
 
Ad

Recently uploaded (20)

PPTX
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
PPTX
𝙳𝚘𝚠𝚗𝚕𝚘𝚊𝚍—Wondershare Filmora Crack 14.0.7 + Key Download 2025
sebastian aliya
 
PDF
“Scaling i.MX Applications Processors’ Native Edge AI with Discrete AI Accele...
Edge AI and Vision Alliance
 
PDF
Why aren't you using FME Flow's CPU Time?
Safe Software
 
PDF
Database Benchmarking for Performance Masterclass: Session 1 - Benchmarking F...
ScyllaDB
 
PPTX
Simplifica la seguridad en la nube y la detección de amenazas con FortiCNAPP
Cristian Garcia G.
 
PPTX
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
PPTX
Practical Applications of AI in Local Government
OnBoard
 
PDF
Plugging AI into everything: Model Context Protocol Simplified.pdf
Abati Adewale
 
PDF
The Growing Value and Application of FME & GenAI
Safe Software
 
PPTX
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
PDF
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
PDF
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
PDF
UiPath Agentic AI ile Akıllı Otomasyonun Yeni Çağı
UiPathCommunity
 
PPTX
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
PDF
Open Source Milvus Vector Database v 2.6
Zilliz
 
PDF
Python Conference Singapore - 19 Jun 2025
ninefyi
 
PDF
Hello I'm "AI" Your New _________________
Dr. Tathagat Varma
 
PDF
Automating the Geo-Referencing of Historic Aerial Photography in Flanders
Safe Software
 
PDF
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
 
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
𝙳𝚘𝚠𝚗𝚕𝚘𝚊𝚍—Wondershare Filmora Crack 14.0.7 + Key Download 2025
sebastian aliya
 
“Scaling i.MX Applications Processors’ Native Edge AI with Discrete AI Accele...
Edge AI and Vision Alliance
 
Why aren't you using FME Flow's CPU Time?
Safe Software
 
Database Benchmarking for Performance Masterclass: Session 1 - Benchmarking F...
ScyllaDB
 
Simplifica la seguridad en la nube y la detección de amenazas con FortiCNAPP
Cristian Garcia G.
 
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
Practical Applications of AI in Local Government
OnBoard
 
Plugging AI into everything: Model Context Protocol Simplified.pdf
Abati Adewale
 
The Growing Value and Application of FME & GenAI
Safe Software
 
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
UiPath Agentic AI ile Akıllı Otomasyonun Yeni Çağı
UiPathCommunity
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
Open Source Milvus Vector Database v 2.6
Zilliz
 
Python Conference Singapore - 19 Jun 2025
ninefyi
 
Hello I'm "AI" Your New _________________
Dr. Tathagat Varma
 
Automating the Geo-Referencing of Historic Aerial Photography in Flanders
Safe Software
 
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
 

Zend Framework 2 - PHPUnit

  • 1. August 25, 2014 Tarun Kumar Singhal ZF2 PHPUnit
  • 2. ZF2 PHPUnit Agenda What is PhpUnit Installation How to write an automated test Writing and running tests with PHPUnit Code-Coverage Analysis Advantages and disadvantages of PhpUnit
  • 3. ZF2 PHPUnit Ballon Effect Testing your application what you build/changed. Retesting everything all the time is very important. That's take a lot of time.
  • 4. ZF2 PHPUnit PhpUnit Testing with PHPUnit means checking that your program behaves as expected, and performing a battery of tests. These runnable code-fragments are called unit tests.
  • 5. ZF2 PHPUnit Installation # pear config-set auto_discover 1 # pear install pear.phpunit.de/PHPUnit // for code coverage # sudo pecl install xdebug
  • 6. ZF2 PHPUnit Directory Tree Structure
  • 7. ZF2 PHPUnit <?php return array( 'modules' => array( TestConfig File //modules needed 'User', 'Products' ), 'module_listener_options' => array( 'config_glob_paths' => array( '../../../config/autoload/{,*.}{global,local,message}.php', ), 'module_paths' => array( 'module', 'vendor', ), ), );
  • 8. ZF2 PHPUnit PhpUnit XML File <?xml version="1.0" encoding="UTF-8"?> <phpunit bootstrap="Bootstrap.php"> <php> <server name="HTTP_HOST" value="http://irizf2.local.com" /> <server name="SERVER_PORT" value="80"/> <server name="REMOTE_ADDR" value=""/> <server name="PDO::MYSQL_ATTR_INIT_COMMAND" value="" /> </php> <testsuites> <testsuite name="Example Controller Tests"> <directory>./UserTest</directory> </testsuite> </testsuites> </phpunit>
  • 9. ZF2 PHPUnit <?php namespace UserTest; // our namespace use ZendLoaderAutoloaderFactory; use ZendMvcServiceServiceManagerConfig; use ZendServiceManagerServiceManager; use ZendSessionContainer; use IridiumAcl; class Bootstrap { public static function init() { // Load the user-defined test configuration file, if it exists; otherwise, load if (is_readable(__DIR__ . '/TestConfig.php')) { $testConfig = include __DIR__ . '/TestConfig.php'; } else { $testConfig = include __DIR__ . '/TestConfig.php.dist'; } …........................ ….......... Bootstrap File
  • 10. ZF2 PHPUnit <?php namespace UserTestController; use ZendTestPHPUnitControllerAbstractHttpControllerTestCase; use ZendTestPHPUnitControllerAbstractControllerTestCase; class AdminControllerTest extends AbstractControllerTestCase { protected $controller; protected $request; protected $response; protected $routeMatch; protected $event; protected $loginForm; protected $userMockObj; protected $callSummaryForm; protected $serviceManager; }
  • 11. ZF2 PHPUnit public function setUp() { $this->serviceManager = Bootstrap::getServiceManager(); $this->controller = new AdminController(); $this->request = new Request(); $tis->routeMatch = new RouteMatch(array('controller' => 'admin')); $this->event = new MvcEvent(); $config = $this->serviceManager->get('Config'); $routerConfig = isset($config['router']) ? $config['router'] : array(); $router = HttpRouter::factory($routerConfig); …............. …........ } PHPUnit supports sharing the setup code. Before a test method is run, a template method called setUp() is invoked. setUp() is where you create the objects against which you will test.
  • 12. ZF2 PHPUnit Writing Tests with PHPUnit // To test the call-summary action public function testCallSummaryAction() { $this->serviceManager->setAllowOverride(true); $this->serviceManager->setService('UserModelUserModel', $this->userMockObj); $this->routeMatch->setParam('action', 'call-summary'); $result = $this->controller->dispatch($this->request); $response = $this->controller->getResponse(); $this->assertEquals(200, $response->getStatusCode()); } //To test the delete-user action public function testDeleteUserAction() { $this->routeMatch->setParam('action', 'delete-user'); $result = $this->controller->dispatch($this->request); $response = $this->controller->getResponse(); $this->assertEquals(302, $response->getStatusCode()); }
  • 13. ZF2 PHPUnit Test class should extend the class AbstractControllerTestCase The tests are public methods that expect no parameters and are named test* Inside the test methods, assertion methods such as assertEquals() are used to assert that an actual value matches an expected value.
  • 14. ZF2 PHPUnit The PHPUnit command-line test runner can be invoked through the phpunit command. # phpunit PHPUnit 4.1.3 by Sebastian Bergmann. .. Time: 00:00 OK (2 tests) . Printed when the test succeeds. F Printed when an assertion fails while running the test method. E Printed when an error occurs while running the test method. S Printed when the test has been skipped. I Printed when the test is marked as being incomplete or not yet implemented.
  • 15. ZF2 PHPUnit Incomplete Tests public function testSomething() { // Stop here and mark this test as incomplete. $this->markTestIncomplete( 'This test has not been implemented yet.‘); } A test as being marked as incomplete or not yet implemented.
  • 16. ZF2 PHPUnit Fixtures setUp() method – is called before a test method run tearDown() method – is called after a test method run setUp() and tearDown() will be called once for each test method run.
  • 17. ZF2 PHPUnit Code-Coverage Analysis How do you find code that is not yet tested? How do you measure testing completeness? #phpunit --coverage-html dir-name PHPUnit 4.1.3 by Sebastian Bergmann. .... Time: 00:00 OK (4 tests) Generating report, this may take a moment.
  • 20. ZF2 PHPUnit Lines of code that were executed while running the tests are highlighted green, lines of code that are executable but were not executed are highlighted red, and "dead code" is highlighted gray.
  • 21. ZF2 PHPUnit Advantages • Testing gives code authors and reviewers confidence that patches produce the correct results. • Detect errors just after code is written • The tests are run at the touch of a button and present their results in a clear format. • Tests run fast • The tests do not affect each other. If some changes are made in one test, the results of others tests do not change.
  • 22. ZF2 PHPUnit Disadvantages Some people have trouble with getting started: where to put the files, how big the scope of one unit test is and when to write a separate testing suite and so on. It would be difficult to write a test for people who are not programmers or familiar with PHP.