SlideShare une entreprise Scribd logo
1  sur  61
Unit testing 101 Introduzione allo Unit Testing in PHP Daniel Londero [email_address]
Chi sono Daniel Londero ,[object Object]
(s|S)ymfony framework
PUG Friuli
GrUSP board
Runner
Attenzione! Assistere alla seguente presentazione può avere i seguenti effetti...
Unit test Seguiti da
Riduzione della pressione arteriosa http://www.flickr.com/photos/fwooper7/4221177229/
Migliore qualità del sonno http://www.flickr.com/photos/paolobosonin/2700153474/
Maggiore tempo libero http://www.flickr.com/photos/73069365@N00/5070251710/ S
Maggiore tempo libero http://www.flickr.com/photos/circumerro-stock/3706572178/
Maggiore tempo libero http://www.flickr.com/photos/limaoscarjuliet/822938133/
Unit testing In computer programming, unit testing is a method by which individual units of source code are tested to determine if they are fit for use. A unit is the smallest testable part of an application. Ideally, each test case is independent from the others: substitutes like method stubs, mock objects, fakes and test harnesses can be used to assist testing a module in isolation.
Unit testing In computer programming, unit testing is a method by which  individual units of source code  are tested to determine if they are fit for use. A unit is the smallest testable part of an application. Ideally, each test case is independent from the others: substitutes like method stubs, mock objects, fakes and test harnesses can be used to assist testing a module in isolation.
Unit testing In computer programming, unit testing is a method by which  individual units of source code  are tested to determine if they are fit for use. A unit is the  smallest testable part  of an application. Ideally, each test case is independent from the others: substitutes like method stubs, mock objects, fakes and test harnesses can be used to assist testing a module in isolation.
Unit testing In computer programming, unit testing is a method by which  individual units of source code  are tested to determine if they are fit for use. A unit is the  smallest testable part  of an application. Ideally, each test case is independent from the others: substitutes like method stubs, mock objects, fakes and test harnesses can be used to assist  testing a module in isolation .
Scusa #1 “Non ho tempo per scrivere i test” oppure “Potrei lavorare ad altre feature nel frattempo”
Regola 80/20 Nuovo codice Manutenzione e debug
...vista dalla parte dello sviluppatore Felicità Tristezza
Funziona Durante  le   operazioni  di debug il codice testato viene eliminato velocemente. Non sarà necessario perdere tempo “ per farlo funzionare ” dato che i test garantiscono il suo funzionamento sin dall'inizio.
Scusa #2 “Nessun altro collega scrive test”
Da solo... http://www.flickr.com/photos/hryckowian/109004281/
Il diverso... http://www.flickr.com/photos/tyrian123/3147557274/
Ma non siamo ragazzini! http://www.flickr.com/photos/feuilllu/302001867/
...inoltre “Nel paese dei ciechi, chi ha un occhio solo è re”
Scusa #3 “Il nostro testing (manuale) è già sufficiente”
Ah sì sicuramente ,[object Object]
Ah sì sicuramente ,[object Object]
Non fai mai un errore
Ah sì sicuramente ,[object Object]
Non fai mai un errore
Controlli  tutti  i test per ogni modifica
Scusa #4 “Scrivere i test è noioso”
Può essere ma... Invece che scriverli  tutti  alla fine basta fare in modo di scriverli prima di implementare la funzionalità (TDD). Il passaggio da scrittura del test a scrittura della feature renderà tutto più divertente.
Vantaggio #1 Meno bug in produzione
Vantaggio #2 Più tempo per lo sviluppo
Vantaggio #3 Test automatici
Vantaggio #4 Facile cambiare. Refactoring.
Vantaggio #5 Miglior design del codice (TDD)
Vantaggio #6 Una forma di documentazione
Vantaggio #7 Focus sul problema
Vantaggio #8 Fiducia
Vantaggio #9 Misurano la completezza
Vantaggio #10 Divertente
Strumenti per PHP
Installare PHPUnit pear channel-discover pear.phpunit.de pear channel-discover components.ez.no pear channel-discover pear.symfony-project.com pear install phpunit/PHPUnit
Convenzioni ,[object Object]
Convenzioni ,[object Object]
ClassTest estende PHPUnit_Framework_TestCase.
Convenzioni ,[object Object]
ClassTest estende PHPUnit_Framework_TestCase.
I test sono metodi pubblici con nome test*.
Convenzioni ,[object Object]
ClassTest estende PHPUnit_Framework_TestCase.
I test sono metodi pubblici con nome test*.
All'interno dei metodi di test, i metodi di asserzione come  assertEquals() vengono utilizzati per verificare che un certo valore corrisponda al valore atteso.
Assertions – Le più comuni AssertTrue/AssertFalse Check the input to verify it equals true/false AssertEquals Check the result against another input for a match AssertGreaterThan Check the result to see if it’s larger than a value AssertContains Check that the input contains a certain value AssertType Check that a variable is of a certain type AssertNull Check that a variable is null AssertFileExists Verify that a file exists AssertRegExp Check the input against a regular expression
Fixtures Una delle cose più dispendiose nella scrittura dei test è la parte relativa al codice per impostare l'ambiente e partire da uno  stato conosciuto  e per poi tornarci alla fine del test. Lo stato conosciuto è chiamato  fixture .
setUp() Il metodo  setUp()  viene invocato prima dell'esecuzione del test. Permette impostare lo stato conosciuto necessario al test.
tearDown() Al termine dell'esecuzione del test viene invocato il metodo  tearDown() . Si occupa delle pulizie.

Contenu connexe

Tendances

Java Unit Testing - JUnit (2)
Java Unit Testing - JUnit (2)Java Unit Testing - JUnit (2)
Java Unit Testing - JUnit (2)fgianneschi
 
Java Unit Testing - Introduction
Java Unit Testing - IntroductionJava Unit Testing - Introduction
Java Unit Testing - Introductionfgianneschi
 
Test Driven Development for iOS
Test Driven Development for iOSTest Driven Development for iOS
Test Driven Development for iOSAlessandro Ceseno
 
Software Testing & Test Driven Development
Software Testing & Test Driven DevelopmentSoftware Testing & Test Driven Development
Software Testing & Test Driven DevelopmentSergio Santoro
 
Java Unit Testing - In container and database testing
Java Unit Testing - In container and database testingJava Unit Testing - In container and database testing
Java Unit Testing - In container and database testingfgianneschi
 
Webinar: “Testing automatico: la scelta vincente per ottenere una riduzione d...
Webinar: “Testing automatico: la scelta vincente per ottenere una riduzione d...Webinar: “Testing automatico: la scelta vincente per ottenere una riduzione d...
Webinar: “Testing automatico: la scelta vincente per ottenere una riduzione d...Emerasoft, solutions to collaborate
 
Android Test Driven Development
Android Test Driven DevelopmentAndroid Test Driven Development
Android Test Driven Developmentsazilla
 
TDD in WordPress
TDD in WordPressTDD in WordPress
TDD in WordPresslucatume
 
Tdd.Every.Where.21012012
Tdd.Every.Where.21012012Tdd.Every.Where.21012012
Tdd.Every.Where.21012012LEGALDESK
 
Mocking Objects Practices
Mocking Objects PracticesMocking Objects Practices
Mocking Objects PracticesGrUSP
 
Py a1 python-unit_testing
Py a1 python-unit_testingPy a1 python-unit_testing
Py a1 python-unit_testingMajong DevJfu
 
Unit Testing Mockito
Unit Testing MockitoUnit Testing Mockito
Unit Testing MockitoLuca S Lopomo
 

Tendances (19)

Java Unit Testing - JUnit (2)
Java Unit Testing - JUnit (2)Java Unit Testing - JUnit (2)
Java Unit Testing - JUnit (2)
 
Java Unit Testing - Introduction
Java Unit Testing - IntroductionJava Unit Testing - Introduction
Java Unit Testing - Introduction
 
Software Testing e TDD
Software Testing e TDDSoftware Testing e TDD
Software Testing e TDD
 
Test Driven Development for iOS
Test Driven Development for iOSTest Driven Development for iOS
Test Driven Development for iOS
 
Software Testing & Test Driven Development
Software Testing & Test Driven DevelopmentSoftware Testing & Test Driven Development
Software Testing & Test Driven Development
 
Java Unit Testing - In container and database testing
Java Unit Testing - In container and database testingJava Unit Testing - In container and database testing
Java Unit Testing - In container and database testing
 
Il testing con zend framework
Il testing con zend frameworkIl testing con zend framework
Il testing con zend framework
 
Webinar: “Testing automatico: la scelta vincente per ottenere una riduzione d...
Webinar: “Testing automatico: la scelta vincente per ottenere una riduzione d...Webinar: “Testing automatico: la scelta vincente per ottenere una riduzione d...
Webinar: “Testing automatico: la scelta vincente per ottenere una riduzione d...
 
Android Test Driven Development
Android Test Driven DevelopmentAndroid Test Driven Development
Android Test Driven Development
 
TDD in WordPress
TDD in WordPressTDD in WordPress
TDD in WordPress
 
PhpUnit
PhpUnitPhpUnit
PhpUnit
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Tdd.Every.Where.21012012
Tdd.Every.Where.21012012Tdd.Every.Where.21012012
Tdd.Every.Where.21012012
 
Unit test
Unit testUnit test
Unit test
 
Mocking Objects Practices
Mocking Objects PracticesMocking Objects Practices
Mocking Objects Practices
 
Java codestyle & tipstricks
Java codestyle & tipstricksJava codestyle & tipstricks
Java codestyle & tipstricks
 
Py a1 python-unit_testing
Py a1 python-unit_testingPy a1 python-unit_testing
Py a1 python-unit_testing
 
Unit Testing Mockito
Unit Testing MockitoUnit Testing Mockito
Unit Testing Mockito
 

Similaire à Unit testing 101

Delphi & Dintorni Webinar - Diventa un mago del Testing
Delphi & Dintorni Webinar - Diventa un mago del TestingDelphi & Dintorni Webinar - Diventa un mago del Testing
Delphi & Dintorni Webinar - Diventa un mago del TestingMarco Breveglieri
 
Consigli per iniziare tdd
Consigli per iniziare tddConsigli per iniziare tdd
Consigli per iniziare tddTassoman ☺
 
Presentazione Testing automatizzato
Presentazione Testing automatizzatoPresentazione Testing automatizzato
Presentazione Testing automatizzatoangelolu
 
DevOpsHeroes 2016 - Realizzare Continouous Integration con SQL Server e Visua...
DevOpsHeroes 2016 - Realizzare Continouous Integration con SQL Server e Visua...DevOpsHeroes 2016 - Realizzare Continouous Integration con SQL Server e Visua...
DevOpsHeroes 2016 - Realizzare Continouous Integration con SQL Server e Visua...Alessandro Alpi
 
CONTINUOUS INTEGRATION CON SQL SERVER
CONTINUOUS INTEGRATION CON SQL SERVERCONTINUOUS INTEGRATION CON SQL SERVER
CONTINUOUS INTEGRATION CON SQL SERVERDotNetCampus
 
DotNetCampus - Continuous Integration con Sql Server
DotNetCampus - Continuous Integration con Sql ServerDotNetCampus - Continuous Integration con Sql Server
DotNetCampus - Continuous Integration con Sql ServerAlessandro Alpi
 
A static Analyzer for Finding Dynamic Programming Errors
A static Analyzer for Finding Dynamic Programming ErrorsA static Analyzer for Finding Dynamic Programming Errors
A static Analyzer for Finding Dynamic Programming ErrorsLino Possamai
 
PowerMock TDD User Group Milano
PowerMock TDD User Group MilanoPowerMock TDD User Group Milano
PowerMock TDD User Group MilanoMassimo Groppelli
 
Il buon programmatore - consigli pratici per una vita felice
Il buon programmatore - consigli pratici per una vita feliceIl buon programmatore - consigli pratici per una vita felice
Il buon programmatore - consigli pratici per una vita feliceAndrea Dottor
 
Presentazione della Tesi di Laurea Specialistica : STRUMENTI PER LA GENERAZIO...
Presentazione della Tesi di Laurea Specialistica : STRUMENTI PER LA GENERAZIO...Presentazione della Tesi di Laurea Specialistica : STRUMENTI PER LA GENERAZIO...
Presentazione della Tesi di Laurea Specialistica : STRUMENTI PER LA GENERAZIO...Boymix81
 
Android Test Driven Development
Android Test Driven DevelopmentAndroid Test Driven Development
Android Test Driven Developmentsazilla
 
Clean android code - Droidcon Italiy 2014
Clean android code - Droidcon Italiy 2014Clean android code - Droidcon Italiy 2014
Clean android code - Droidcon Italiy 2014Fabio Collini
 
PASS Virtual Chapter - SQL Server Continuous Integration
PASS Virtual Chapter - SQL Server Continuous IntegrationPASS Virtual Chapter - SQL Server Continuous Integration
PASS Virtual Chapter - SQL Server Continuous IntegrationAlessandro Alpi
 
Googletest, tdd e mock
Googletest, tdd e mockGoogletest, tdd e mock
Googletest, tdd e mockyuroller
 
Clean android code
Clean android codeClean android code
Clean android codefirenze-gtug
 
Tech Webinar: Test e2e per AngularJS e non solo
Tech Webinar: Test e2e per AngularJS e non soloTech Webinar: Test e2e per AngularJS e non solo
Tech Webinar: Test e2e per AngularJS e non soloCodemotion
 

Similaire à Unit testing 101 (20)

Delphi & Dintorni Webinar - Diventa un mago del Testing
Delphi & Dintorni Webinar - Diventa un mago del TestingDelphi & Dintorni Webinar - Diventa un mago del Testing
Delphi & Dintorni Webinar - Diventa un mago del Testing
 
Il testing con zend framework
Il testing con zend frameworkIl testing con zend framework
Il testing con zend framework
 
Consigli per iniziare tdd
Consigli per iniziare tddConsigli per iniziare tdd
Consigli per iniziare tdd
 
Total Testing in DevOps
Total Testing in DevOpsTotal Testing in DevOps
Total Testing in DevOps
 
TTT - Test, Tools and Tips - jug roma
TTT - Test, Tools and Tips - jug romaTTT - Test, Tools and Tips - jug roma
TTT - Test, Tools and Tips - jug roma
 
Presentazione Testing automatizzato
Presentazione Testing automatizzatoPresentazione Testing automatizzato
Presentazione Testing automatizzato
 
DevOpsHeroes 2016 - Realizzare Continouous Integration con SQL Server e Visua...
DevOpsHeroes 2016 - Realizzare Continouous Integration con SQL Server e Visua...DevOpsHeroes 2016 - Realizzare Continouous Integration con SQL Server e Visua...
DevOpsHeroes 2016 - Realizzare Continouous Integration con SQL Server e Visua...
 
CONTINUOUS INTEGRATION CON SQL SERVER
CONTINUOUS INTEGRATION CON SQL SERVERCONTINUOUS INTEGRATION CON SQL SERVER
CONTINUOUS INTEGRATION CON SQL SERVER
 
DotNetCampus - Continuous Integration con Sql Server
DotNetCampus - Continuous Integration con Sql ServerDotNetCampus - Continuous Integration con Sql Server
DotNetCampus - Continuous Integration con Sql Server
 
A static Analyzer for Finding Dynamic Programming Errors
A static Analyzer for Finding Dynamic Programming ErrorsA static Analyzer for Finding Dynamic Programming Errors
A static Analyzer for Finding Dynamic Programming Errors
 
PowerMock TDD User Group Milano
PowerMock TDD User Group MilanoPowerMock TDD User Group Milano
PowerMock TDD User Group Milano
 
Il buon programmatore - consigli pratici per una vita felice
Il buon programmatore - consigli pratici per una vita feliceIl buon programmatore - consigli pratici per una vita felice
Il buon programmatore - consigli pratici per una vita felice
 
Presentazione della Tesi di Laurea Specialistica : STRUMENTI PER LA GENERAZIO...
Presentazione della Tesi di Laurea Specialistica : STRUMENTI PER LA GENERAZIO...Presentazione della Tesi di Laurea Specialistica : STRUMENTI PER LA GENERAZIO...
Presentazione della Tesi di Laurea Specialistica : STRUMENTI PER LA GENERAZIO...
 
Android Test Driven Development
Android Test Driven DevelopmentAndroid Test Driven Development
Android Test Driven Development
 
Clean android code - Droidcon Italiy 2014
Clean android code - Droidcon Italiy 2014Clean android code - Droidcon Italiy 2014
Clean android code - Droidcon Italiy 2014
 
Workshop: Introduzione ad TDD
Workshop: Introduzione ad TDDWorkshop: Introduzione ad TDD
Workshop: Introduzione ad TDD
 
PASS Virtual Chapter - SQL Server Continuous Integration
PASS Virtual Chapter - SQL Server Continuous IntegrationPASS Virtual Chapter - SQL Server Continuous Integration
PASS Virtual Chapter - SQL Server Continuous Integration
 
Googletest, tdd e mock
Googletest, tdd e mockGoogletest, tdd e mock
Googletest, tdd e mock
 
Clean android code
Clean android codeClean android code
Clean android code
 
Tech Webinar: Test e2e per AngularJS e non solo
Tech Webinar: Test e2e per AngularJS e non soloTech Webinar: Test e2e per AngularJS e non solo
Tech Webinar: Test e2e per AngularJS e non solo
 

Plus de Daniel Londero

Random Tips for Remote Working
Random Tips for Remote WorkingRandom Tips for Remote Working
Random Tips for Remote WorkingDaniel Londero
 
REST in practice with Symfony2
REST in practice with Symfony2REST in practice with Symfony2
REST in practice with Symfony2Daniel Londero
 
Rest in practice con Symfony2
Rest in practice con Symfony2Rest in practice con Symfony2
Rest in practice con Symfony2Daniel Londero
 
Lavorare da casa: siamo pronti?
Lavorare da casa: siamo pronti?Lavorare da casa: siamo pronti?
Lavorare da casa: siamo pronti?Daniel Londero
 
Symfony2, SQL e NoSQL. Assieme. Si può.
Symfony2, SQL e NoSQL. Assieme. Si può.Symfony2, SQL e NoSQL. Assieme. Si può.
Symfony2, SQL e NoSQL. Assieme. Si può.Daniel Londero
 
Lavorare da casa: siamo pronti?
Lavorare da casa: siamo pronti?Lavorare da casa: siamo pronti?
Lavorare da casa: siamo pronti?Daniel Londero
 
Symfony e grandi numeri: si può fare!
Symfony e grandi numeri: si può fare!Symfony e grandi numeri: si può fare!
Symfony e grandi numeri: si può fare!Daniel Londero
 
Enterprise Open Source: Il caso PHP
Enterprise Open Source: Il caso PHPEnterprise Open Source: Il caso PHP
Enterprise Open Source: Il caso PHPDaniel Londero
 

Plus de Daniel Londero (10)

Magento meets vagrant
Magento meets vagrantMagento meets vagrant
Magento meets vagrant
 
Random Tips for Remote Working
Random Tips for Remote WorkingRandom Tips for Remote Working
Random Tips for Remote Working
 
REST in practice with Symfony2
REST in practice with Symfony2REST in practice with Symfony2
REST in practice with Symfony2
 
Rest in practice con Symfony2
Rest in practice con Symfony2Rest in practice con Symfony2
Rest in practice con Symfony2
 
Lavorare da casa: siamo pronti?
Lavorare da casa: siamo pronti?Lavorare da casa: siamo pronti?
Lavorare da casa: siamo pronti?
 
Symfony2, SQL e NoSQL. Assieme. Si può.
Symfony2, SQL e NoSQL. Assieme. Si può.Symfony2, SQL e NoSQL. Assieme. Si può.
Symfony2, SQL e NoSQL. Assieme. Si può.
 
Lavorare da casa: siamo pronti?
Lavorare da casa: siamo pronti?Lavorare da casa: siamo pronti?
Lavorare da casa: siamo pronti?
 
Io cache, tu database
Io cache, tu databaseIo cache, tu database
Io cache, tu database
 
Symfony e grandi numeri: si può fare!
Symfony e grandi numeri: si può fare!Symfony e grandi numeri: si può fare!
Symfony e grandi numeri: si può fare!
 
Enterprise Open Source: Il caso PHP
Enterprise Open Source: Il caso PHPEnterprise Open Source: Il caso PHP
Enterprise Open Source: Il caso PHP
 

Dernier

Federico Bottino, Lead Venture Builder – “Riflessioni sull’Innovazione: La Cu...
Federico Bottino, Lead Venture Builder – “Riflessioni sull’Innovazione: La Cu...Federico Bottino, Lead Venture Builder – “Riflessioni sull’Innovazione: La Cu...
Federico Bottino, Lead Venture Builder – “Riflessioni sull’Innovazione: La Cu...Associazione Digital Days
 
Edoardo Di Pietro – “Virtual Influencer vs Umano: Rubiamo il lavoro all’AI”
Edoardo Di Pietro – “Virtual Influencer vs Umano: Rubiamo il lavoro all’AI”Edoardo Di Pietro – “Virtual Influencer vs Umano: Rubiamo il lavoro all’AI”
Edoardo Di Pietro – “Virtual Influencer vs Umano: Rubiamo il lavoro all’AI”Associazione Digital Days
 
Luigi Di Carlo, CEO & Founder @Evometrika srl – “Ruolo della computer vision ...
Luigi Di Carlo, CEO & Founder @Evometrika srl – “Ruolo della computer vision ...Luigi Di Carlo, CEO & Founder @Evometrika srl – “Ruolo della computer vision ...
Luigi Di Carlo, CEO & Founder @Evometrika srl – “Ruolo della computer vision ...Associazione Digital Days
 
Alessandro Nasi, COO @Djungle Studio – “Cosa delegheresti alla copia di te st...
Alessandro Nasi, COO @Djungle Studio – “Cosa delegheresti alla copia di te st...Alessandro Nasi, COO @Djungle Studio – “Cosa delegheresti alla copia di te st...
Alessandro Nasi, COO @Djungle Studio – “Cosa delegheresti alla copia di te st...Associazione Digital Days
 
Alessio Mazzotti, Aaron Brancotti; Writer, Screenwriter, Director, UX, Autore...
Alessio Mazzotti, Aaron Brancotti; Writer, Screenwriter, Director, UX, Autore...Alessio Mazzotti, Aaron Brancotti; Writer, Screenwriter, Director, UX, Autore...
Alessio Mazzotti, Aaron Brancotti; Writer, Screenwriter, Director, UX, Autore...Associazione Digital Days
 
Gabriele Mittica, CEO @Corley Cloud – “Come creare un’azienda “nativa in clou...
Gabriele Mittica, CEO @Corley Cloud – “Come creare un’azienda “nativa in clou...Gabriele Mittica, CEO @Corley Cloud – “Come creare un’azienda “nativa in clou...
Gabriele Mittica, CEO @Corley Cloud – “Come creare un’azienda “nativa in clou...Associazione Digital Days
 
Daniele Lunassi, CEO & Head of Design @Eye Studios – “Creare prodotti e servi...
Daniele Lunassi, CEO & Head of Design @Eye Studios – “Creare prodotti e servi...Daniele Lunassi, CEO & Head of Design @Eye Studios – “Creare prodotti e servi...
Daniele Lunassi, CEO & Head of Design @Eye Studios – “Creare prodotti e servi...Associazione Digital Days
 
ScrapeGraphAI: a new way to scrape context with AI
ScrapeGraphAI: a new way to scrape context with AIScrapeGraphAI: a new way to scrape context with AI
ScrapeGraphAI: a new way to scrape context with AIinfogdgmi
 
Mael Chiabrera, Software Developer; Viola Bongini, Digital Experience Designe...
Mael Chiabrera, Software Developer; Viola Bongini, Digital Experience Designe...Mael Chiabrera, Software Developer; Viola Bongini, Digital Experience Designe...
Mael Chiabrera, Software Developer; Viola Bongini, Digital Experience Designe...Associazione Digital Days
 

Dernier (9)

Federico Bottino, Lead Venture Builder – “Riflessioni sull’Innovazione: La Cu...
Federico Bottino, Lead Venture Builder – “Riflessioni sull’Innovazione: La Cu...Federico Bottino, Lead Venture Builder – “Riflessioni sull’Innovazione: La Cu...
Federico Bottino, Lead Venture Builder – “Riflessioni sull’Innovazione: La Cu...
 
Edoardo Di Pietro – “Virtual Influencer vs Umano: Rubiamo il lavoro all’AI”
Edoardo Di Pietro – “Virtual Influencer vs Umano: Rubiamo il lavoro all’AI”Edoardo Di Pietro – “Virtual Influencer vs Umano: Rubiamo il lavoro all’AI”
Edoardo Di Pietro – “Virtual Influencer vs Umano: Rubiamo il lavoro all’AI”
 
Luigi Di Carlo, CEO & Founder @Evometrika srl – “Ruolo della computer vision ...
Luigi Di Carlo, CEO & Founder @Evometrika srl – “Ruolo della computer vision ...Luigi Di Carlo, CEO & Founder @Evometrika srl – “Ruolo della computer vision ...
Luigi Di Carlo, CEO & Founder @Evometrika srl – “Ruolo della computer vision ...
 
Alessandro Nasi, COO @Djungle Studio – “Cosa delegheresti alla copia di te st...
Alessandro Nasi, COO @Djungle Studio – “Cosa delegheresti alla copia di te st...Alessandro Nasi, COO @Djungle Studio – “Cosa delegheresti alla copia di te st...
Alessandro Nasi, COO @Djungle Studio – “Cosa delegheresti alla copia di te st...
 
Alessio Mazzotti, Aaron Brancotti; Writer, Screenwriter, Director, UX, Autore...
Alessio Mazzotti, Aaron Brancotti; Writer, Screenwriter, Director, UX, Autore...Alessio Mazzotti, Aaron Brancotti; Writer, Screenwriter, Director, UX, Autore...
Alessio Mazzotti, Aaron Brancotti; Writer, Screenwriter, Director, UX, Autore...
 
Gabriele Mittica, CEO @Corley Cloud – “Come creare un’azienda “nativa in clou...
Gabriele Mittica, CEO @Corley Cloud – “Come creare un’azienda “nativa in clou...Gabriele Mittica, CEO @Corley Cloud – “Come creare un’azienda “nativa in clou...
Gabriele Mittica, CEO @Corley Cloud – “Come creare un’azienda “nativa in clou...
 
Daniele Lunassi, CEO & Head of Design @Eye Studios – “Creare prodotti e servi...
Daniele Lunassi, CEO & Head of Design @Eye Studios – “Creare prodotti e servi...Daniele Lunassi, CEO & Head of Design @Eye Studios – “Creare prodotti e servi...
Daniele Lunassi, CEO & Head of Design @Eye Studios – “Creare prodotti e servi...
 
ScrapeGraphAI: a new way to scrape context with AI
ScrapeGraphAI: a new way to scrape context with AIScrapeGraphAI: a new way to scrape context with AI
ScrapeGraphAI: a new way to scrape context with AI
 
Mael Chiabrera, Software Developer; Viola Bongini, Digital Experience Designe...
Mael Chiabrera, Software Developer; Viola Bongini, Digital Experience Designe...Mael Chiabrera, Software Developer; Viola Bongini, Digital Experience Designe...
Mael Chiabrera, Software Developer; Viola Bongini, Digital Experience Designe...
 

Unit testing 101

  • 1. Unit testing 101 Introduzione allo Unit Testing in PHP Daniel Londero [email_address]
  • 2.
  • 7. Attenzione! Assistere alla seguente presentazione può avere i seguenti effetti...
  • 9. Riduzione della pressione arteriosa http://www.flickr.com/photos/fwooper7/4221177229/
  • 10. Migliore qualità del sonno http://www.flickr.com/photos/paolobosonin/2700153474/
  • 11. Maggiore tempo libero http://www.flickr.com/photos/73069365@N00/5070251710/ S
  • 12. Maggiore tempo libero http://www.flickr.com/photos/circumerro-stock/3706572178/
  • 13. Maggiore tempo libero http://www.flickr.com/photos/limaoscarjuliet/822938133/
  • 14. Unit testing In computer programming, unit testing is a method by which individual units of source code are tested to determine if they are fit for use. A unit is the smallest testable part of an application. Ideally, each test case is independent from the others: substitutes like method stubs, mock objects, fakes and test harnesses can be used to assist testing a module in isolation.
  • 15. Unit testing In computer programming, unit testing is a method by which individual units of source code are tested to determine if they are fit for use. A unit is the smallest testable part of an application. Ideally, each test case is independent from the others: substitutes like method stubs, mock objects, fakes and test harnesses can be used to assist testing a module in isolation.
  • 16. Unit testing In computer programming, unit testing is a method by which individual units of source code are tested to determine if they are fit for use. A unit is the smallest testable part of an application. Ideally, each test case is independent from the others: substitutes like method stubs, mock objects, fakes and test harnesses can be used to assist testing a module in isolation.
  • 17. Unit testing In computer programming, unit testing is a method by which individual units of source code are tested to determine if they are fit for use. A unit is the smallest testable part of an application. Ideally, each test case is independent from the others: substitutes like method stubs, mock objects, fakes and test harnesses can be used to assist testing a module in isolation .
  • 18. Scusa #1 “Non ho tempo per scrivere i test” oppure “Potrei lavorare ad altre feature nel frattempo”
  • 19. Regola 80/20 Nuovo codice Manutenzione e debug
  • 20. ...vista dalla parte dello sviluppatore Felicità Tristezza
  • 21. Funziona Durante le operazioni di debug il codice testato viene eliminato velocemente. Non sarà necessario perdere tempo “ per farlo funzionare ” dato che i test garantiscono il suo funzionamento sin dall'inizio.
  • 22. Scusa #2 “Nessun altro collega scrive test”
  • 25. Ma non siamo ragazzini! http://www.flickr.com/photos/feuilllu/302001867/
  • 26. ...inoltre “Nel paese dei ciechi, chi ha un occhio solo è re”
  • 27. Scusa #3 “Il nostro testing (manuale) è già sufficiente”
  • 28.
  • 29.
  • 30. Non fai mai un errore
  • 31.
  • 32. Non fai mai un errore
  • 33. Controlli tutti i test per ogni modifica
  • 34. Scusa #4 “Scrivere i test è noioso”
  • 35. Può essere ma... Invece che scriverli tutti alla fine basta fare in modo di scriverli prima di implementare la funzionalità (TDD). Il passaggio da scrittura del test a scrittura della feature renderà tutto più divertente.
  • 36. Vantaggio #1 Meno bug in produzione
  • 37. Vantaggio #2 Più tempo per lo sviluppo
  • 38. Vantaggio #3 Test automatici
  • 39. Vantaggio #4 Facile cambiare. Refactoring.
  • 40. Vantaggio #5 Miglior design del codice (TDD)
  • 41. Vantaggio #6 Una forma di documentazione
  • 42. Vantaggio #7 Focus sul problema
  • 44. Vantaggio #9 Misurano la completezza
  • 47. Installare PHPUnit pear channel-discover pear.phpunit.de pear channel-discover components.ez.no pear channel-discover pear.symfony-project.com pear install phpunit/PHPUnit
  • 48.
  • 49.
  • 51.
  • 53. I test sono metodi pubblici con nome test*.
  • 54.
  • 56. I test sono metodi pubblici con nome test*.
  • 57. All'interno dei metodi di test, i metodi di asserzione come assertEquals() vengono utilizzati per verificare che un certo valore corrisponda al valore atteso.
  • 58. Assertions – Le più comuni AssertTrue/AssertFalse Check the input to verify it equals true/false AssertEquals Check the result against another input for a match AssertGreaterThan Check the result to see if it’s larger than a value AssertContains Check that the input contains a certain value AssertType Check that a variable is of a certain type AssertNull Check that a variable is null AssertFileExists Verify that a file exists AssertRegExp Check the input against a regular expression
  • 59. Fixtures Una delle cose più dispendiose nella scrittura dei test è la parte relativa al codice per impostare l'ambiente e partire da uno stato conosciuto e per poi tornarci alla fine del test. Lo stato conosciuto è chiamato fixture .
  • 60. setUp() Il metodo setUp() viene invocato prima dell'esecuzione del test. Permette impostare lo stato conosciuto necessario al test.
  • 61. tearDown() Al termine dell'esecuzione del test viene invocato il metodo tearDown() . Si occupa delle pulizie.
  • 62. Doubles “ Sometimes it is just plain hard to test the system under test (SUT) because it depends on other components that cannot be used in the test environment. This could be because they aren't available, they will not return the results needed for the test or because executing them would have undesirable side effects. In other cases, our test strategy requires us to have more control or visibility of the internal behavior of the SUT. When we are writing a test in which we cannot (or chose not to) use a real depended-on component (DOC), we can replace it with a Test Double. The Test Double doesn't have to behave exactly like the real DOC; it merely has to provide the same API as the real one so that the SUT thinks it is the real one!” --Gerard Meszaros
  • 63. Stub Oggetto appositamente configurato per restituire valori predefiniti. Rimpiazza un oggetto reale dal quale dipende is SUT. Permette di avere il controllo sugli input indiretti del SUT.
  • 64. Stub - esempio <?php class SomeClass { public function doSomething() { // Do something. } } ?>
  • 65. Stub - esempio <?php require_once 'SomeClass.php'; class StubTest extends PHPUnit_Framework_TestCase { public function testStub() { // Create a stub for the SomeClass class. $stub = $this->getMock('SomeClass'); // Configure the stub. $stub->expects($this->any()) ->method('doSomething') ->will($this->returnValue('foo')); // Calling $stub->doSomething() will now return // 'foo'. $this->assertEquals('foo', $stub->doSomething()); } } ?>
  • 66. Mock Oggetto appositamente configurato per verificare delle aspettative, come per esempio la chiamata di un metodo specifico. Punto di osservazione utilizzato per verificare gli output indiretti del SUT mentre è in esecuzione.
  • 67. Mock - esempio <?php class Subject { protected $observers = array(); public function attach(Observer $observer) { $this->observers[] = $observer; } public function doSomething() { // Do something. // ... // Notify observers that we did something. $this->notify('something'); } protected function notify($argument) { foreach ($this->observers as $observer) { $observer->update($argument); } } // Other methods. }
  • 68. Mock - esempio class Observer { public function update($argument) { // Do something. } public function reportError($errorCode, $errorMessage, Subject $subject) { // Do something } // Other methods. } ?>
  • 69. Mock - esempio <?php class SubjectTest extends PHPUnit_Framework_TestCase { public function testObserversAreUpdated() { // Create a mock for the Observer class, // only mock the update() method. $observer = $this->getMock('Observer', array('update')); // Set up the expectation for the update() method // to be called only once and with the string 'something' // as its parameter. $observer->expects($this->once()) ->method('update') ->with($this->equalTo('something')); // Create a Subject object and attach the mocked // Observer object to it. $subject = new Subject; $subject->attach($observer); // Call the doSomething() method on the $subject object // which we expect to call the mocked Observer object's // update() method with the string 'something'. $subject->doSomething(); } } ?>
  • 70. Sporchiamoci le mani Bowling game kata
  • 71. ?
  • 72. Credits http://www.phpunit.de/manual/3.5/en/index.html http://www.masukomi.org/talks/unit_testing_talk_2/index.xul http://devzone.zend.com/article/2772 http://www.sitepoint.com/tutorial-introduction-to-unit-testing-in-php-with-phpunit/ http://www.slideshare.net/sebastian_bergmann/quality-assurance-in-php-projects-presentation

Notes de l'éditeur

  1. Una pratica che permette di verificare che singole unità di codice facciano effettivamente ciò per cui sono state scritte. Un&apos;unità è la più piccola parte delle&apos;applicazione. Nel caso ideale ogni test è indipendente dagli altri: per ottenere quest&apos;isolamento possiamo ricorrere all&apos;utilizzo di stubs, mocks, fakes...
  2. Le chiavi della definizione sono le seguenti: parliamo di singole unità di codice
  3. ...dove l&apos;unità di codice è la più piccola parte testabile dell&apos;applicazione: - PROCEDURALE: intero programma, funzioni - OO: metodi
  4. Il vincolo è quello di poter testare la singola unità di codice in ISOLAMENTO dal resto dell&apos;applicazione.
  5. Legittima se non si conoscono i test... La regola dell&apos;80/20...
  6. Perchè? Perchè non hai test. Rompi il codice e tu non lo sai. Un altro dev rompe il tuo codice e tu non lo sai. Tu rompi il codice dell&apos;altro dev e lui non lo sa.
  7. Ecco quindi che il “non ho tempo” significa “non ho tempo di imparare a testare il codice e voglio solo scrivere codice reale ORA”. Pigrizia Poca lungimiranza
  8. La locuzione latina Beati monoculi in terra caecorum (pronuncia: beàti monòculi in tèrra cecòrum)
  9. Lanciare la suite di test frequentemente permette di individuare i bug. E&apos; inevitabile. Individuare i bug subito permette di risolverli più facilmente dato che il codice è ancora “fresco” in testa. Inoltre si possono aggiungere nuovi test per bug extra prima di fixarli per essere sicuri di cosa si sta modificando.
  10. Individuare e risolvere i bug poco tempo dopo la loro introduzione è molto più veloce che trovare, analizzare e risolvere un bug tra 1 o 6 mesi. Inoltre si evita di rompere altre parti dell&apos;applicazione con l&apos;inserimento di nuove feature.
  11. Automatizzare l&apos;esecuzione della suite di test è il valore in più. Possono essere lanciati velocemente da console o da un refresh del browser. Verificano tutto. Il costo di scrittura è una-tantum, vengono eseguiti migliaia di volte. GRATIS.
  12. Modificare un metodo mantenendo inalterati i dati che restituisce. Inserire nuove funzionalità senza rompere le altre. Senza test non è possibile fare REFACTORING.
  13. Scrivere i test spinge a pensare maggiormente come mantenere le cose semplici: disaccoppiate e flessibili. Si traduce in facilità di test. Se è difficile da testare non è ben progettato. Se è troppo corposo potrebbe essere necessario separare le cose in classi diverse...
  14. Il test descrive un caso d&apos;uso o un esempio. Un esempio spesso vale più di mille parole. &amp;quot;testdox&amp;quot; strumento che elenca (sfruttando i nomi dei metodi) ciò che l&apos;esempio asserisce. Essenzialmente rappresenta una specifica delle classi più leggibile per i non sviluppatori (DBA).
  15. Un errore comune è quello di buttarsi a capofitto nello scrivere codice senza una strategia ben definita. Come essere in una stanza buia, ci si muove a tentativi tornando indietro per poi ripartire perdendo un sacco di tempo per trovare l&apos;uscita. Dovendo scrivere i test si è obbligati a pensare al problema in modo diverso per trovare soluzioni semplici, eleganti e pratiche. E&apos; più facile andare avanti, tornare indietro è raro.
  16. Poter verificare il codice, individuare bug più facilmente, apportare modifiche senza correre rischi permette di spendere più tempo sviluppando nuove feature invece che risolvendo problemi. Si guarda sempre avanti.
  17. Se si sono scritti test per coprire tutte le feature richieste e tutti passano è ragionevole pensare che il codice sia finito. Questo si mischia bene con le pratiche XP/Agile dove i test servono anche per verificare i requisiti funzionali.
  18. Avere fiducia nel proprio codice, poter cambiare facilmente le cose, risolvere i problemi con criterio ed in modo elegante, poter fare refactoring sono tutte cose che fanno apprezzare il processo.
  19. Nella documentazione trovate tutte le assertion disponibili, vi assicuro che ce ne sono davvero molte...
  20. setUp() and tearDown() are nicely symmetrical in theory but not in practice. In practice, you only need to implement tearDown() if you have allocated external resources like files or sockets in setUp(). If your setUp() just creates plain PHP objects, you can generally ignore tearDown(). However, if you create many objects in your setUp(), you might want to unset() the variables pointing to those objects in your tearDown() so they can be garbage collected. The garbage collection of test case objects is not predictable.
  21. Nella definizione di unit testing abbiamo visto che eseguire i testi in isolamento è importante. A volte non possiamo utilizzare i componenti reali da cui dipende ciò che stiamo testando ecco quindi che entrano in campo i Double. Un Double rimpiazza un DOC. Un Double non dev&apos;essere per forza uguale al DOC che rimpiazza, deve avere la stessa API per far credere al sistema che si tratta del componente vero!