SlideShare une entreprise Scribd logo
1  sur  40
Télécharger pour lire hors ligne
PHPunit
Episode IV.III!
Return of the tests
A long time ago,
in a code base not so far away…
For years people have been advocating the
usage of unit tests and slowly developers
around the world have adopted the skills to write
good tests. But since the crisis businesses have
been battling for customers and profits, leaving
less room for proper QA and testing. In this race
for money, things are looking dim and
unfavourable for businesses that have cut
corners and went straight for the gold.
Fortunately it’s not to late for development teams
to turn the tide and reclaim their honour and
ensure businesses aren’t disposing money out of
the window because of easily preventable
failures. The gloves are on and developers take
action to test what’s most important: the core of
the applications!
Auth ACL
Products
Customer
Details
Front-End
Back-End
Business
Logic
External
Services
RDBMS
Files
NoSQL
Streams
Auth ACL
Business
Logic
External
Services
Auth ACL
Business
Logic
External
Services
Mocked!
External!
Services
https://www.flickr.com/photos/noodlepie/3886519163
https://www.flickr.com/photos/cseeman/11101920756
https://www.flickr.com/photos/st3f4n/3752994778
Your class contains 10K lines!
I sense lots of anger in you
https://www.flickr.com/photos/clement127/16162227260
• createOrder
• updateOrder
• payOrder
• cancelOrder
• findOrderById
• findOrderByCustomerId
• findOrderByPaymentId
• createOrder
• updateOrder
• payOrder
• findOrderByPaymentId
• findOrderByCustomerId
• findOrderById
• cancelOrder
} High importance
} Normal importance
} Low importance
    /** "
     * Creates an order based on provided data "
     * "
     * @param array $data Associative array with order information "
     * @return bool|int Will return the order ID if storage was successful "
     * or false when storage failed "
     */ "
    public function createOrder($data) "
    { "
        $db = Registry::getInstance()->get('db'); "
        $sql = sprintf( "
            'INSERT INTO `order` (`productId`, `customerId`, "
            `productPrice`, `quantity`) VALUES (%d, %d, %f, %f)', "
            $data['productId'], $data['customerId'], "
            $data['productPrice'], $data['quantity'] "
        ); "
        $id = false; "
        try { "
            $id = $db->exec($sql); "
        } catch (Exception $e) { "
            Registry::get('logger')->log($e->getMessage(), CRIT); "
            Registry::get('logger')->log($e->getTraceAsString(), INFO); "
        } "
        return $id; "
    }
https://www.flickr.com/photos/simononly/16445278475
/** "
 * Creates an order based on provided data "
 * "
 * @param array $data Associative array with order information "
 * @return bool|int Will return the order ID if storage was successful  "
 * or false when storage failed "
 */ "
public function createOrder($data) "
{ "
    $db = Registry::get('db'); "
    $sql = sprintf( "
        'INSERT INTO `order` (`productId`, `customerId`,  "
        `productPrice`, `quantity`) VALUES (%d, %d, %f, %f)', "
        $data['productId'], $data['customerId'],  "
        $data['productPrice'], $data['quantity'] "
    ); "
    $id = false; "
    try { "
        $id = $db->query($sql); "
    } catch (Exception $e) { "
        Registry::get('logger')->log($e->getMessage(), CRIT); "
        Registry::get('logger')->log($e->getTraceAsString(), INFO); "
    } "
    return $id; "
}
/** "
 * Creates an order based on provided data "
 * "
 * @param array $data Associative array with order information "
 * @return bool|int Will return the order ID if storage was successful  "
 * or false when storage failed "
 */ "
public function createOrder($data) "
{ "
    $db = Registry::get('db'); "
    $sql = sprintf( "
        'INSERT INTO `order` (`productId`, `customerId`,  "
        `productPrice`, `quantity`) VALUES (%d, %d, %f, %f)', "
        $data['productId'], $data['customerId'],  "
        $data['productPrice'], $data['quantity'] "
    ); "
    $id = false; "
    try { "
        $id = $db->query($sql); "
    } catch (Exception $e) { "
        Registry::get('logger')->log($e->getMessage(), CRIT); "
        Registry::get('logger')->log($e->getTraceAsString(), INFO); "
    } "
    return $id; "
}
/** "
 * Creates an order based on provided data "
 * "
 * @param array $data Associative array with order information "
 * @return bool|int Will return the order ID if storage was successful  "
 * or false when storage failed "
 */ "
public function createOrder($data) "
{ "
    $db = Registry::get('db'); "
    $sql = sprintf( "
        'INSERT INTO `order` (`productId`, `customerId`,  "
        `productPrice`, `quantity`) VALUES (%d, %d, %f, %f)', "
        $data['productId'], $data['customerId'],  "
        $data['productPrice'], $data['quantity'] "
    ); "
    $id = false; "
    try { "
        $id = $db->query($sql); "
    } catch (Exception $e) { "
        Registry::get('logger')->log($e->getMessage(), CRIT); "
        Registry::get('logger')->log($e->getTraceAsString(), INFO); "
    } "
    return $id; "
}
What do we know?
What do we know?
• We provide an array with values in
What do we know?
• We provide an array with values in
• We get inserted ID or false back
What do we know?
• We provide an array with values in
• We get inserted ID or false back
• The code is crappy
class OrderTest extends PHPUnit_Framework_TestCase "
{ "
    public function testCreateOrder() "
    { "
        $data = array ( "
            'productId' => 1, "
            'customerId' => 1, "
            'productPrice' => 4.95, "
            'quantity' => 2, "
        ); "
        $order = new Order(); "
        $result = $order->createOrder($data); "
        $this->assertGreaterThanOrEqual(1, $result); "
    } "
}
    public function testCreateOrder() "
    { "
        $db = new PDO('sqlite::memory:'); "
        $db->exec('CREATE TABLE `order` ( "
          `orderId` INTEGER PRIMARY KEY NOT NULL, "
          `productId` INTEGER NOT NULL, "
          `customerId` INTEGER NOT NULL, "
          `productPrice` REAL NOT NULL DEFAULT 0.0, "
          `quantity` REAL NOT NULL DEFAULT 1.0);'); "
        Registry::getInstance()->register('db', $db); "
        $data = array ( "
            'productId' => 1, "
            'customerId' => 1, "
            'productPrice' => 4.95, "
            'quantity' => 2, "
        ); "
        $order = new Order(); "
        $result = $order->createOrder($data); "
        $this->assertGreaterThanOrEqual(1, $result); "
    }
https://www.flickr.com/photos/jurvetson/83176915
    public function testCreateOrder() "
    { "
        $db = $this->getMock('PDO',  "
            array ('exec'), array ('sqlite::memory:')); "
        $db->expects($this->once()) "
            ->method('exec') "
            ->will($this->returnValue(2)); "
!
        Registry::getInstance()->register('db', $db); "
        $data = array ( "
            'productId' => 1, "
            'customerId' => 1, "
            'productPrice' => 4.95, "
            'quantity' => 2, "
        ); "
        $order = new Order(); "
        $result = $order->createOrder($data); "
        $this->assertGreaterThanOrEqual(1, $result); "
    }
https://www.flickr.com/photos/legofenris/4578453569
    /** "
     * @var PDO "
     */ "
    protected $db; "
!
    /** "
     * @return PDO "
     */ "
    public function getDb() "
    { "
        if (null === $this->db) { "
            // fallback to old functions using this method "
            $this->setDb(Registry::getInstance()->get('db')); "
        } "
        return $this->db; "
    } "
!
    /** "
     * @param PDO $db "
     */ "
    public function setDb($db) "
    { "
        $this->db = $db; "
    }
    /** "
     * Creates an order based on provided data "
     * "
     * @param array $data Associative array with order information "
     * @return bool|int Will return the order ID if storage was successful "
     * or false when storage failed "
     */ "
    public function createOrder($data) "
    { "
        $db = $this->getDb(); "
        $sql = sprintf( "
            'INSERT INTO `order` (`productId`, `customerId`, "
            `productPrice`, `quantity`) VALUES (%d, %d, %f, %f)', "
            $data['productId'], $data['customerId'], "
            $data['productPrice'], $data['quantity'] "
        ); "
        $id = false; "
        try { "
            $id = $db->exec($sql); "
        } catch (Exception $e) { "
            Registry::get('logger')->log($e->getMessage(), CRIT); "
            Registry::get('logger')->log($e->getTraceAsString(), INFO); "
        } "
        return $id; "
    }
https://www.flickr.com/photos/pasukaru76/5152497973
Michelangelo van Dam
dragonbe@gmail
T DragonBe
F DragonBe
www.dragonbe.com
Intergalactic PHP Ninja Consultant
https://www.flickr.com/photos/130160246@N02/16465367556
joind.in/event/view/3701
Rate my talk
If you liked it, thanks.
If you don’t, tell me how to improve it
https://www.flickr.com/photos/toomuchdew/14508564745

Contenu connexe

Tendances

UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013Michelangelo van Dam
 
Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Konstantin Kudryashov
 
Building a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing StrategiesBuilding a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing StrategiesCiaranMcNulty
 
How to test complex SaaS applications - The family july 2014
How to test complex SaaS applications - The family july 2014How to test complex SaaS applications - The family july 2014
How to test complex SaaS applications - The family july 2014Guillaume POTIER
 
Proposed PHP function: is_literal()
Proposed PHP function: is_literal()Proposed PHP function: is_literal()
Proposed PHP function: is_literal()Craig Francis
 
Refactoring using Codeception
Refactoring using CodeceptionRefactoring using Codeception
Refactoring using CodeceptionJeroen van Dijk
 
Top 5 Magento Secure Coding Best Practices
Top 5 Magento Secure Coding Best PracticesTop 5 Magento Secure Coding Best Practices
Top 5 Magento Secure Coding Best PracticesOleksandr Zarichnyi
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in actionJace Ju
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в MagentoMagecom Ukraine
 
Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016Colin O'Dell
 
Manipulating Magento - Meet Magento Netherlands 2018
Manipulating Magento - Meet Magento Netherlands 2018Manipulating Magento - Meet Magento Netherlands 2018
Manipulating Magento - Meet Magento Netherlands 2018Joke Puts
 
Introduction to Zend Framework web services
Introduction to Zend Framework web servicesIntroduction to Zend Framework web services
Introduction to Zend Framework web servicesMichelangelo van Dam
 
05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboardsDenis Ristic
 
Decoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICDecoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICKonstantin Kudryashov
 

Tendances (20)

UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Frontin like-a-backer
Frontin like-a-backerFrontin like-a-backer
Frontin like-a-backer
 
Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015
 
PHPSpec BDD for PHP
PHPSpec BDD for PHPPHPSpec BDD for PHP
PHPSpec BDD for PHP
 
Building a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing StrategiesBuilding a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing Strategies
 
How to test complex SaaS applications - The family july 2014
How to test complex SaaS applications - The family july 2014How to test complex SaaS applications - The family july 2014
How to test complex SaaS applications - The family july 2014
 
Proposed PHP function: is_literal()
Proposed PHP function: is_literal()Proposed PHP function: is_literal()
Proposed PHP function: is_literal()
 
Refactoring using Codeception
Refactoring using CodeceptionRefactoring using Codeception
Refactoring using Codeception
 
Min-Maxing Software Costs
Min-Maxing Software CostsMin-Maxing Software Costs
Min-Maxing Software Costs
 
Top 5 Magento Secure Coding Best Practices
Top 5 Magento Secure Coding Best PracticesTop 5 Magento Secure Coding Best Practices
Top 5 Magento Secure Coding Best Practices
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in action
 
New in php 7
New in php 7New in php 7
New in php 7
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в Magento
 
Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016
 
Manipulating Magento - Meet Magento Netherlands 2018
Manipulating Magento - Meet Magento Netherlands 2018Manipulating Magento - Meet Magento Netherlands 2018
Manipulating Magento - Meet Magento Netherlands 2018
 
CakePHP workshop
CakePHP workshopCakePHP workshop
CakePHP workshop
 
Introduction to Zend Framework web services
Introduction to Zend Framework web servicesIntroduction to Zend Framework web services
Introduction to Zend Framework web services
 
05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards
 
Decoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICDecoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DIC
 

En vedette (6)

Guitarita
GuitaritaGuitarita
Guitarita
 
Construccion En Dubai
Construccion En DubaiConstruccion En Dubai
Construccion En Dubai
 
07.05.20
07.05.2007.05.20
07.05.20
 
El Passat I El Futur En El Present
El Passat I El Futur En El PresentEl Passat I El Futur En El Present
El Passat I El Futur En El Present
 
Java EE6 Overview
Java EE6 OverviewJava EE6 Overview
Java EE6 Overview
 
L Univers
L UniversL Univers
L Univers
 

Similaire à PHPUnit Episode iv.iii: Return of the tests

TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...
TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...
TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...tdc-globalcode
 
Agile data presentation 3 - cambridge
Agile data   presentation 3 - cambridgeAgile data   presentation 3 - cambridge
Agile data presentation 3 - cambridgeRomans Malinovskis
 
Spca2014 hillier 3rd party_javascript_libraries
Spca2014 hillier 3rd party_javascript_librariesSpca2014 hillier 3rd party_javascript_libraries
Spca2014 hillier 3rd party_javascript_librariesNCCOMMS
 
PHP Experience 2016 - [Workshop] Elastic Search: Turbinando sua aplicação PHP
PHP Experience 2016 - [Workshop] Elastic Search: Turbinando sua aplicação PHPPHP Experience 2016 - [Workshop] Elastic Search: Turbinando sua aplicação PHP
PHP Experience 2016 - [Workshop] Elastic Search: Turbinando sua aplicação PHPiMasters
 
Web internship Yii Framework
Web internship  Yii FrameworkWeb internship  Yii Framework
Web internship Yii FrameworkNoveo
 
CiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForceCiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForceCiklum Ukraine
 
GraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learnedGraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learnedMarcinStachniuk
 
Taking Web Apps Offline
Taking Web Apps OfflineTaking Web Apps Offline
Taking Web Apps OfflinePedro Morais
 
TechDays 2013 Jari Kallonen: What's New WebForms 4.5
TechDays 2013 Jari Kallonen: What's New WebForms 4.5TechDays 2013 Jari Kallonen: What's New WebForms 4.5
TechDays 2013 Jari Kallonen: What's New WebForms 4.5Tieturi Oy
 
Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecturepostrational
 
Data Mining Open Ap Is
Data Mining Open Ap IsData Mining Open Ap Is
Data Mining Open Ap Isoscon2007
 
Implementation of GUI Framework part3
Implementation of GUI Framework part3Implementation of GUI Framework part3
Implementation of GUI Framework part3masahiroookubo
 
Crafting Quality PHP Applications: an overview (PHPSW March 2018)
Crafting Quality PHP Applications: an overview (PHPSW March 2018)Crafting Quality PHP Applications: an overview (PHPSW March 2018)
Crafting Quality PHP Applications: an overview (PHPSW March 2018)James Titcumb
 
Web Forms People Don't Hate
Web Forms People Don't HateWeb Forms People Don't Hate
Web Forms People Don't Hatecliener
 
Dublin Ireland Spark Meetup October 15, 2015
Dublin Ireland Spark Meetup October 15, 2015Dublin Ireland Spark Meetup October 15, 2015
Dublin Ireland Spark Meetup October 15, 2015eddiebaggott
 
How to convert custom plsql to web services-Soap OR Rest
How to convert custom plsql to web services-Soap OR RestHow to convert custom plsql to web services-Soap OR Rest
How to convert custom plsql to web services-Soap OR Restshravan kumar chelika
 
Security: Odoo Code Hardening
Security: Odoo Code HardeningSecurity: Odoo Code Hardening
Security: Odoo Code HardeningOdoo
 
HTML5 Gaming Payment Platforms
HTML5 Gaming Payment PlatformsHTML5 Gaming Payment Platforms
HTML5 Gaming Payment PlatformsJonathan LeBlanc
 

Similaire à PHPUnit Episode iv.iii: Return of the tests (20)

TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...
TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...
TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...
 
Agile data presentation 3 - cambridge
Agile data   presentation 3 - cambridgeAgile data   presentation 3 - cambridge
Agile data presentation 3 - cambridge
 
Spca2014 hillier 3rd party_javascript_libraries
Spca2014 hillier 3rd party_javascript_librariesSpca2014 hillier 3rd party_javascript_libraries
Spca2014 hillier 3rd party_javascript_libraries
 
PHP Experience 2016 - [Workshop] Elastic Search: Turbinando sua aplicação PHP
PHP Experience 2016 - [Workshop] Elastic Search: Turbinando sua aplicação PHPPHP Experience 2016 - [Workshop] Elastic Search: Turbinando sua aplicação PHP
PHP Experience 2016 - [Workshop] Elastic Search: Turbinando sua aplicação PHP
 
Webauthn Tutorial
Webauthn TutorialWebauthn Tutorial
Webauthn Tutorial
 
Web internship Yii Framework
Web internship  Yii FrameworkWeb internship  Yii Framework
Web internship Yii Framework
 
MySQL under the siege
MySQL under the siegeMySQL under the siege
MySQL under the siege
 
CiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForceCiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForce
 
GraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learnedGraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learned
 
Taking Web Apps Offline
Taking Web Apps OfflineTaking Web Apps Offline
Taking Web Apps Offline
 
TechDays 2013 Jari Kallonen: What's New WebForms 4.5
TechDays 2013 Jari Kallonen: What's New WebForms 4.5TechDays 2013 Jari Kallonen: What's New WebForms 4.5
TechDays 2013 Jari Kallonen: What's New WebForms 4.5
 
Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecture
 
Data Mining Open Ap Is
Data Mining Open Ap IsData Mining Open Ap Is
Data Mining Open Ap Is
 
Implementation of GUI Framework part3
Implementation of GUI Framework part3Implementation of GUI Framework part3
Implementation of GUI Framework part3
 
Crafting Quality PHP Applications: an overview (PHPSW March 2018)
Crafting Quality PHP Applications: an overview (PHPSW March 2018)Crafting Quality PHP Applications: an overview (PHPSW March 2018)
Crafting Quality PHP Applications: an overview (PHPSW March 2018)
 
Web Forms People Don't Hate
Web Forms People Don't HateWeb Forms People Don't Hate
Web Forms People Don't Hate
 
Dublin Ireland Spark Meetup October 15, 2015
Dublin Ireland Spark Meetup October 15, 2015Dublin Ireland Spark Meetup October 15, 2015
Dublin Ireland Spark Meetup October 15, 2015
 
How to convert custom plsql to web services-Soap OR Rest
How to convert custom plsql to web services-Soap OR RestHow to convert custom plsql to web services-Soap OR Rest
How to convert custom plsql to web services-Soap OR Rest
 
Security: Odoo Code Hardening
Security: Odoo Code HardeningSecurity: Odoo Code Hardening
Security: Odoo Code Hardening
 
HTML5 Gaming Payment Platforms
HTML5 Gaming Payment PlatformsHTML5 Gaming Payment Platforms
HTML5 Gaming Payment Platforms
 

Plus de Michelangelo van Dam

GDPR Art. 25 - Privacy by design and default
GDPR Art. 25 - Privacy by design and defaultGDPR Art. 25 - Privacy by design and default
GDPR Art. 25 - Privacy by design and defaultMichelangelo van Dam
 
Moving from app services to azure functions
Moving from app services to azure functionsMoving from app services to azure functions
Moving from app services to azure functionsMichelangelo van Dam
 
General Data Protection Regulation, a developer's story
General Data Protection Regulation, a developer's storyGeneral Data Protection Regulation, a developer's story
General Data Protection Regulation, a developer's storyMichelangelo van Dam
 
Leveraging a distributed architecture to your advantage
Leveraging a distributed architecture to your advantageLeveraging a distributed architecture to your advantage
Leveraging a distributed architecture to your advantageMichelangelo van Dam
 
Open source for a successful business
Open source for a successful businessOpen source for a successful business
Open source for a successful businessMichelangelo van Dam
 
Decouple your framework now, thank me later
Decouple your framework now, thank me laterDecouple your framework now, thank me later
Decouple your framework now, thank me laterMichelangelo van Dam
 
Deploy to azure in less then 15 minutes
Deploy to azure in less then 15 minutesDeploy to azure in less then 15 minutes
Deploy to azure in less then 15 minutesMichelangelo van Dam
 
Azure and OSS, a match made in heaven
Azure and OSS, a match made in heavenAzure and OSS, a match made in heaven
Azure and OSS, a match made in heavenMichelangelo van Dam
 
Easily extend your existing php app with an api
Easily extend your existing php app with an apiEasily extend your existing php app with an api
Easily extend your existing php app with an apiMichelangelo van Dam
 

Plus de Michelangelo van Dam (20)

GDPR Art. 25 - Privacy by design and default
GDPR Art. 25 - Privacy by design and defaultGDPR Art. 25 - Privacy by design and default
GDPR Art. 25 - Privacy by design and default
 
Moving from app services to azure functions
Moving from app services to azure functionsMoving from app services to azure functions
Moving from app services to azure functions
 
Privacy by design
Privacy by designPrivacy by design
Privacy by design
 
DevOps or DevSecOps
DevOps or DevSecOpsDevOps or DevSecOps
DevOps or DevSecOps
 
Privacy by design
Privacy by designPrivacy by design
Privacy by design
 
Continuous deployment 2.0
Continuous deployment 2.0Continuous deployment 2.0
Continuous deployment 2.0
 
Let your tests drive your code
Let your tests drive your codeLet your tests drive your code
Let your tests drive your code
 
General Data Protection Regulation, a developer's story
General Data Protection Regulation, a developer's storyGeneral Data Protection Regulation, a developer's story
General Data Protection Regulation, a developer's story
 
Leveraging a distributed architecture to your advantage
Leveraging a distributed architecture to your advantageLeveraging a distributed architecture to your advantage
Leveraging a distributed architecture to your advantage
 
The road to php 7.1
The road to php 7.1The road to php 7.1
The road to php 7.1
 
Open source for a successful business
Open source for a successful businessOpen source for a successful business
Open source for a successful business
 
Decouple your framework now, thank me later
Decouple your framework now, thank me laterDecouple your framework now, thank me later
Decouple your framework now, thank me later
 
Deploy to azure in less then 15 minutes
Deploy to azure in less then 15 minutesDeploy to azure in less then 15 minutes
Deploy to azure in less then 15 minutes
 
Azure and OSS, a match made in heaven
Azure and OSS, a match made in heavenAzure and OSS, a match made in heaven
Azure and OSS, a match made in heaven
 
Getting hands dirty with php7
Getting hands dirty with php7Getting hands dirty with php7
Getting hands dirty with php7
 
Create, test, secure, repeat
Create, test, secure, repeatCreate, test, secure, repeat
Create, test, secure, repeat
 
The Continuous PHP Pipeline
The Continuous PHP PipelineThe Continuous PHP Pipeline
The Continuous PHP Pipeline
 
Easily extend your existing php app with an api
Easily extend your existing php app with an apiEasily extend your existing php app with an api
Easily extend your existing php app with an api
 
Your code are my tests
Your code are my testsYour code are my tests
Your code are my tests
 
200K+ reasons security is a must
200K+ reasons security is a must200K+ reasons security is a must
200K+ reasons security is a must
 

Dernier

data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)simmis5
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01KreezheaRecto
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...SUHANI PANDEY
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfKamal Acharya
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxfenichawla
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueBhangaleSonal
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXssuser89054b
 

Dernier (20)

data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 

PHPUnit Episode iv.iii: Return of the tests

  • 2. A long time ago, in a code base not so far away…
  • 3. For years people have been advocating the usage of unit tests and slowly developers around the world have adopted the skills to write good tests. But since the crisis businesses have been battling for customers and profits, leaving less room for proper QA and testing. In this race for money, things are looking dim and unfavourable for businesses that have cut corners and went straight for the gold.
  • 4. Fortunately it’s not to late for development teams to turn the tide and reclaim their honour and ensure businesses aren’t disposing money out of the window because of easily preventable failures. The gloves are on and developers take action to test what’s most important: the core of the applications!
  • 5.
  • 6.
  • 7.
  • 15. • createOrder • updateOrder • payOrder • cancelOrder • findOrderById • findOrderByCustomerId • findOrderByPaymentId
  • 16. • createOrder • updateOrder • payOrder • findOrderByPaymentId • findOrderByCustomerId • findOrderById • cancelOrder } High importance } Normal importance } Low importance
  • 17.     /** "      * Creates an order based on provided data "      * "      * @param array $data Associative array with order information "      * @return bool|int Will return the order ID if storage was successful "      * or false when storage failed "      */ "     public function createOrder($data) "     { "         $db = Registry::getInstance()->get('db'); "         $sql = sprintf( "             'INSERT INTO `order` (`productId`, `customerId`, "             `productPrice`, `quantity`) VALUES (%d, %d, %f, %f)', "             $data['productId'], $data['customerId'], "             $data['productPrice'], $data['quantity'] "         ); "         $id = false; "         try { "             $id = $db->exec($sql); "         } catch (Exception $e) { "             Registry::get('logger')->log($e->getMessage(), CRIT); "             Registry::get('logger')->log($e->getTraceAsString(), INFO); "         } "         return $id; "     }
  • 19. /** "  * Creates an order based on provided data "  * "  * @param array $data Associative array with order information "  * @return bool|int Will return the order ID if storage was successful  "  * or false when storage failed "  */ " public function createOrder($data) " { "     $db = Registry::get('db'); "     $sql = sprintf( "         'INSERT INTO `order` (`productId`, `customerId`,  "         `productPrice`, `quantity`) VALUES (%d, %d, %f, %f)', "         $data['productId'], $data['customerId'],  "         $data['productPrice'], $data['quantity'] "     ); "     $id = false; "     try { "         $id = $db->query($sql); "     } catch (Exception $e) { "         Registry::get('logger')->log($e->getMessage(), CRIT); "         Registry::get('logger')->log($e->getTraceAsString(), INFO); "     } "     return $id; " }
  • 20. /** "  * Creates an order based on provided data "  * "  * @param array $data Associative array with order information "  * @return bool|int Will return the order ID if storage was successful  "  * or false when storage failed "  */ " public function createOrder($data) " { "     $db = Registry::get('db'); "     $sql = sprintf( "         'INSERT INTO `order` (`productId`, `customerId`,  "         `productPrice`, `quantity`) VALUES (%d, %d, %f, %f)', "         $data['productId'], $data['customerId'],  "         $data['productPrice'], $data['quantity'] "     ); "     $id = false; "     try { "         $id = $db->query($sql); "     } catch (Exception $e) { "         Registry::get('logger')->log($e->getMessage(), CRIT); "         Registry::get('logger')->log($e->getTraceAsString(), INFO); "     } "     return $id; " }
  • 21. /** "  * Creates an order based on provided data "  * "  * @param array $data Associative array with order information "  * @return bool|int Will return the order ID if storage was successful  "  * or false when storage failed "  */ " public function createOrder($data) " { "     $db = Registry::get('db'); "     $sql = sprintf( "         'INSERT INTO `order` (`productId`, `customerId`,  "         `productPrice`, `quantity`) VALUES (%d, %d, %f, %f)', "         $data['productId'], $data['customerId'],  "         $data['productPrice'], $data['quantity'] "     ); "     $id = false; "     try { "         $id = $db->query($sql); "     } catch (Exception $e) { "         Registry::get('logger')->log($e->getMessage(), CRIT); "         Registry::get('logger')->log($e->getTraceAsString(), INFO); "     } "     return $id; " }
  • 22. What do we know?
  • 23. What do we know? • We provide an array with values in
  • 24. What do we know? • We provide an array with values in • We get inserted ID or false back
  • 25. What do we know? • We provide an array with values in • We get inserted ID or false back • The code is crappy
  • 26. class OrderTest extends PHPUnit_Framework_TestCase " { "     public function testCreateOrder() "     { "         $data = array ( "             'productId' => 1, "             'customerId' => 1, "             'productPrice' => 4.95, "             'quantity' => 2, "         ); "         $order = new Order(); "         $result = $order->createOrder($data); "         $this->assertGreaterThanOrEqual(1, $result); "     } " }
  • 27.
  • 28.     public function testCreateOrder() "     { "         $db = new PDO('sqlite::memory:'); "         $db->exec('CREATE TABLE `order` ( "           `orderId` INTEGER PRIMARY KEY NOT NULL, "           `productId` INTEGER NOT NULL, "           `customerId` INTEGER NOT NULL, "           `productPrice` REAL NOT NULL DEFAULT 0.0, "           `quantity` REAL NOT NULL DEFAULT 1.0);'); "         Registry::getInstance()->register('db', $db); "         $data = array ( "             'productId' => 1, "             'customerId' => 1, "             'productPrice' => 4.95, "             'quantity' => 2, "         ); "         $order = new Order(); "         $result = $order->createOrder($data); "         $this->assertGreaterThanOrEqual(1, $result); "     }
  • 29.
  • 31.     public function testCreateOrder() "     { "         $db = $this->getMock('PDO',  "             array ('exec'), array ('sqlite::memory:')); "         $db->expects($this->once()) "             ->method('exec') "             ->will($this->returnValue(2)); " !         Registry::getInstance()->register('db', $db); "         $data = array ( "             'productId' => 1, "             'customerId' => 1, "             'productPrice' => 4.95, "             'quantity' => 2, "         ); "         $order = new Order(); "         $result = $order->createOrder($data); "         $this->assertGreaterThanOrEqual(1, $result); "     }
  • 32.
  • 34.     /** "      * @var PDO "      */ "     protected $db; " !     /** "      * @return PDO "      */ "     public function getDb() "     { "         if (null === $this->db) { "             // fallback to old functions using this method "             $this->setDb(Registry::getInstance()->get('db')); "         } "         return $this->db; "     } " !     /** "      * @param PDO $db "      */ "     public function setDb($db) "     { "         $this->db = $db; "     }
  • 35.     /** "      * Creates an order based on provided data "      * "      * @param array $data Associative array with order information "      * @return bool|int Will return the order ID if storage was successful "      * or false when storage failed "      */ "     public function createOrder($data) "     { "         $db = $this->getDb(); "         $sql = sprintf( "             'INSERT INTO `order` (`productId`, `customerId`, "             `productPrice`, `quantity`) VALUES (%d, %d, %f, %f)', "             $data['productId'], $data['customerId'], "             $data['productPrice'], $data['quantity'] "         ); "         $id = false; "         try { "             $id = $db->exec($sql); "         } catch (Exception $e) { "             Registry::get('logger')->log($e->getMessage(), CRIT); "             Registry::get('logger')->log($e->getTraceAsString(), INFO); "         } "         return $id; "     }
  • 36.
  • 38. Michelangelo van Dam dragonbe@gmail T DragonBe F DragonBe www.dragonbe.com Intergalactic PHP Ninja Consultant https://www.flickr.com/photos/130160246@N02/16465367556
  • 39. joind.in/event/view/3701 Rate my talk If you liked it, thanks. If you don’t, tell me how to improve it