SlideShare ist ein Scribd-Unternehmen logo
1 von 40
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Andere mochten auch

Andere mochten auch (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Call Girls Mumbai
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsvanyagupta248
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdfAldoGarca30
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXssuser89054b
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . pptDineshKumar4165
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.Kamal Acharya
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdfKamal Acharya
 
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxOrlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxMuhammadAsimMuhammad6
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdfKamal Acharya
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdfKamal Acharya
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startQuintin Balsdon
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxJuliansyahHarahap1
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"mphochane1998
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayEpec Engineered Technologies
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...Amil baba
 
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
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdfKamal Acharya
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityMorshed Ahmed Rahath
 
Verification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptxVerification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptxchumtiyababu
 

Kürzlich hochgeladen (20)

Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech students
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
 
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxOrlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdf
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdf
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
 
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
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
Verification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptxVerification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptx
 

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