SlideShare a Scribd company logo
1 of 10
How to write
not breakable unit tests?
Based on PHPUnit
by Rafal Ksiazek, IT Leader
https://github.com/harpcio
Agenda
• The old aproach - mocking everything
– Pros and cons
• The new aproach – using real objects
– Pros and cons
• What we should mock?
• The magic of real objects
• How to mock?
The old aproach – mock everything
<?php
namespace Model;
class Car {
public function __construct(EngineInterface $engine) {
$this->engine = $engine;
}
public function run() {
$this->engine->start();
$this->engine->accelerate(10);
}
public function getActualSpeed() {
return $this->engine->getSpeed();
}
}
<?php
namespace TestsModel;
class CarTest {
public function setUp() {
$this->engineMock = $this->getMock(
TestsManualEngine::class
);
$this->testedObject = new Car(
$this->engineMock
);
}
public function testRun() {
$this->engineMock->expects($this->once())
->method(`start`);
$this->engineMock->expects($this->once())
->method(`accelerate`);
$this->testedObject->run();
$this->assertSame(
10,
$this->testedObject->getActualSpeed()
);
}
….
}
The old aproach – pros and cons
Pros:
• when class Engine fail, the
CarTest will still be valid
(tests are separated)
Cons:
• writing tests are more time
consuming
• changing class Engine, we
need to change also class
CarTest
• there is no possibility that
we will find not tested
functionality (forgotten or
skiped) in class Engine
The new aproach – use real objects
<?php
namespace Model;
class Car {
public function __construct(EngineInterface $engine) {
$this->engine = $engine;
}
public function run() {
$this->engine->start();
$this->engine->accelerate(10);
}
public function getActualSpeed() {
return $this->engine->getSpeed();
}
}
<?php
namespace TestsModel;
class CarTest {
public function setUp() {
$this->testedObject = new Car(
new Engine()
);
}
public function testRun() {
$this->testedObject->run();
$this->assertSame(
10,
$this->testedObject->getActualSpeed()
);
}
….
}
The new aproach – pros and cons
Pros:
• writing tests are much faster
• changing class Engine, we
don’t need to change also
class CarTest
• there is possibility that we
will find not tested
functionality (forgotten or
skiped) in class Engine
Cons:
• when class Engine fail, the
CarTest will also fail (but
fixing class Engine will fix
also CarTest)
What we should mock?
• We should mock classes that cross the border
of business logic layer, for example:
– Repositories (data access layer)
– File managers (file system layer)
– Connectors (facebook, twitter, google oauth)
The magic of real objects
<?php
namespace MyAppTestsRepository;
class UsersArrayRepository implement UsersRepositoryInterface {
public function __construct(array $users = []) {
$this->container = $users;
}
public function delete(User $user) {
foreach($this->container as $key => $elem) {
if ($elem->getId() === $user->getId()) {
unset($this->container[$key]);
return true;
}
}
return false;
}
…
}
How to mock
<?php
namespace MyAppService;
class UsersCrud {
public function __construct(
UsersRepositoryInterface $usersRepository
) {
$this->usersRepository = $usersRepository;
}
public function delete($userId) {
$user = $this->usersRepository->find($userId);
if (!$user) {
throw new UserNotFoundException();
}
return $this->usersRepository->delete($user);
}
}
<?php
namespace MyAppTestsService;
class UsersCrud Test {
public function setUp() {
$this->testedObject = new UsersCrud (
new UsersArrayRepository(
12 => new User()
)
);
}
public function testDelete_WhenSuccess() {
$result = $this->testedObject->delete(12);
$this->assertTrue($result);
}
….
}
Summary
• changing name of method „delete” to
„deleteOnlyDeacitivatedUser” in UsersRepository will force
change in the class „UsersCrud” and „UsersRepositoryTest”,
but not in the „UsersCrudTest”
• so .. we can do a lot of refactoring without worrying about
tests, hundreds of classes which use UsersRepository uwill
change automatically by IDE and tests of these classes will still
be valid
• thx for watching!

More Related Content

What's hot

Upgrade your javascript to drupal 8
Upgrade your javascript to drupal 8Upgrade your javascript to drupal 8
Upgrade your javascript to drupal 8Théodore Biadala
 
Алексей Плеханов: Новинки Laravel 5
Алексей Плеханов: Новинки Laravel 5Алексей Плеханов: Новинки Laravel 5
Алексей Плеханов: Новинки Laravel 5Oleg Poludnenko
 
Doctrine Internals. UnitOfWork
Doctrine Internals. UnitOfWorkDoctrine Internals. UnitOfWork
Doctrine Internals. UnitOfWorkAndrew Yatsenko
 
(SDD414) Amazon Redshift Deep Dive and What's Next | AWS re:Invent 2014
(SDD414) Amazon Redshift Deep Dive and What's Next | AWS re:Invent 2014(SDD414) Amazon Redshift Deep Dive and What's Next | AWS re:Invent 2014
(SDD414) Amazon Redshift Deep Dive and What's Next | AWS re:Invent 2014Amazon Web Services
 
Ditching JQuery
Ditching JQueryDitching JQuery
Ditching JQueryhowlowck
 
Laravel, the right way - PHPConference 2016
Laravel, the right way - PHPConference 2016Laravel, the right way - PHPConference 2016
Laravel, the right way - PHPConference 2016Matheus Marabesi
 
Let's write secure Drupal code! DUG Belgium - 08/08/2019
Let's write secure Drupal code! DUG Belgium - 08/08/2019Let's write secure Drupal code! DUG Belgium - 08/08/2019
Let's write secure Drupal code! DUG Belgium - 08/08/2019Balázs Tatár
 
Playing nice with others
Playing nice with othersPlaying nice with others
Playing nice with othersEric Mann
 
16.mysql stored procedures in laravel
16.mysql stored procedures in laravel16.mysql stored procedures in laravel
16.mysql stored procedures in laravelRazvan Raducanu, PhD
 
Gary Gao: APIs Are Good
Gary Gao: APIs Are GoodGary Gao: APIs Are Good
Gary Gao: APIs Are Goodtalnoznisky
 
Clear php reference
Clear php referenceClear php reference
Clear php referenceDamien Seguy
 
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur..."How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...Fwdays
 

What's hot (20)

Upgrade your javascript to drupal 8
Upgrade your javascript to drupal 8Upgrade your javascript to drupal 8
Upgrade your javascript to drupal 8
 
Алексей Плеханов: Новинки Laravel 5
Алексей Плеханов: Новинки Laravel 5Алексей Плеханов: Новинки Laravel 5
Алексей Плеханов: Новинки Laravel 5
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
 
jdbc
jdbcjdbc
jdbc
 
Laravel the right way
Laravel   the right wayLaravel   the right way
Laravel the right way
 
Doctrine Internals. UnitOfWork
Doctrine Internals. UnitOfWorkDoctrine Internals. UnitOfWork
Doctrine Internals. UnitOfWork
 
(SDD414) Amazon Redshift Deep Dive and What's Next | AWS re:Invent 2014
(SDD414) Amazon Redshift Deep Dive and What's Next | AWS re:Invent 2014(SDD414) Amazon Redshift Deep Dive and What's Next | AWS re:Invent 2014
(SDD414) Amazon Redshift Deep Dive and What's Next | AWS re:Invent 2014
 
Ditching JQuery
Ditching JQueryDitching JQuery
Ditching JQuery
 
Getting Started-with-Laravel
Getting Started-with-LaravelGetting Started-with-Laravel
Getting Started-with-Laravel
 
Laravel, the right way - PHPConference 2016
Laravel, the right way - PHPConference 2016Laravel, the right way - PHPConference 2016
Laravel, the right way - PHPConference 2016
 
Let's write secure Drupal code! DUG Belgium - 08/08/2019
Let's write secure Drupal code! DUG Belgium - 08/08/2019Let's write secure Drupal code! DUG Belgium - 08/08/2019
Let's write secure Drupal code! DUG Belgium - 08/08/2019
 
Mojolicious
MojoliciousMojolicious
Mojolicious
 
Playing nice with others
Playing nice with othersPlaying nice with others
Playing nice with others
 
16.mysql stored procedures in laravel
16.mysql stored procedures in laravel16.mysql stored procedures in laravel
16.mysql stored procedures in laravel
 
DIG1108 Lesson 6
DIG1108 Lesson 6DIG1108 Lesson 6
DIG1108 Lesson 6
 
Gary Gao: APIs Are Good
Gary Gao: APIs Are GoodGary Gao: APIs Are Good
Gary Gao: APIs Are Good
 
Clear php reference
Clear php referenceClear php reference
Clear php reference
 
Silex Cheat Sheet
Silex Cheat SheetSilex Cheat Sheet
Silex Cheat Sheet
 
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur..."How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
 
4.2 PHP Function
4.2 PHP Function4.2 PHP Function
4.2 PHP Function
 

Similar to How to write not breakable unit tests

Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applicationschartjes
 
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur PurnamaEPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur PurnamaEnterprise PHP Center
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐいHisateru Tanaka
 
ZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectJonathan Wage
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Fwdays
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?Nikita Popov
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalystdwm042
 
Как получить чёрный пояс по WordPress?
Как получить чёрный пояс по WordPress?Как получить чёрный пояс по WordPress?
Как получить чёрный пояс по WordPress?Yevhen Kotelnytskyi
 
Functional Javascript
Functional JavascriptFunctional Javascript
Functional Javascriptguest4d57e6
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptGuy Royse
 
Php on the desktop and php gtk2
Php on the desktop and php gtk2Php on the desktop and php gtk2
Php on the desktop and php gtk2Elizabeth Smith
 
Auto-loading of Drupal CCK Nodes
Auto-loading of Drupal CCK NodesAuto-loading of Drupal CCK Nodes
Auto-loading of Drupal CCK Nodesnihiliad
 
Why should we use an INTERFACE even when we only have one concrete class?
Why should we use an INTERFACE even when we only have one concrete class?Why should we use an INTERFACE even when we only have one concrete class?
Why should we use an INTERFACE even when we only have one concrete class?Rafal Ksiazek
 
Load Testing with PHP and RedLine13
Load Testing with PHP and RedLine13Load Testing with PHP and RedLine13
Load Testing with PHP and RedLine13Jason Lotito
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosDivante
 
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)arcware
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Michelangelo van Dam
 
Using Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkUsing Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkDirk Haun
 

Similar to How to write not breakable unit tests (20)

Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur PurnamaEPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
ZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine Project
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
 
Как получить чёрный пояс по WordPress?
Как получить чёрный пояс по WordPress?Как получить чёрный пояс по WordPress?
Как получить чёрный пояс по WordPress?
 
Functional Javascript
Functional JavascriptFunctional Javascript
Functional Javascript
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
 
Php on the desktop and php gtk2
Php on the desktop and php gtk2Php on the desktop and php gtk2
Php on the desktop and php gtk2
 
Auto-loading of Drupal CCK Nodes
Auto-loading of Drupal CCK NodesAuto-loading of Drupal CCK Nodes
Auto-loading of Drupal CCK Nodes
 
Why should we use an INTERFACE even when we only have one concrete class?
Why should we use an INTERFACE even when we only have one concrete class?Why should we use an INTERFACE even when we only have one concrete class?
Why should we use an INTERFACE even when we only have one concrete class?
 
Load Testing with PHP and RedLine13
Load Testing with PHP and RedLine13Load Testing with PHP and RedLine13
Load Testing with PHP and RedLine13
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenarios
 
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010
 
Using Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkUsing Geeklog as a Web Application Framework
Using Geeklog as a Web Application Framework
 

Recently uploaded

%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyAnusha Are
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxalwaysnagaraju26
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfryanfarris8
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedDelhi Call girls
 

Recently uploaded (20)

%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodology
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 

How to write not breakable unit tests

  • 1. How to write not breakable unit tests? Based on PHPUnit by Rafal Ksiazek, IT Leader https://github.com/harpcio
  • 2. Agenda • The old aproach - mocking everything – Pros and cons • The new aproach – using real objects – Pros and cons • What we should mock? • The magic of real objects • How to mock?
  • 3. The old aproach – mock everything <?php namespace Model; class Car { public function __construct(EngineInterface $engine) { $this->engine = $engine; } public function run() { $this->engine->start(); $this->engine->accelerate(10); } public function getActualSpeed() { return $this->engine->getSpeed(); } } <?php namespace TestsModel; class CarTest { public function setUp() { $this->engineMock = $this->getMock( TestsManualEngine::class ); $this->testedObject = new Car( $this->engineMock ); } public function testRun() { $this->engineMock->expects($this->once()) ->method(`start`); $this->engineMock->expects($this->once()) ->method(`accelerate`); $this->testedObject->run(); $this->assertSame( 10, $this->testedObject->getActualSpeed() ); } …. }
  • 4. The old aproach – pros and cons Pros: • when class Engine fail, the CarTest will still be valid (tests are separated) Cons: • writing tests are more time consuming • changing class Engine, we need to change also class CarTest • there is no possibility that we will find not tested functionality (forgotten or skiped) in class Engine
  • 5. The new aproach – use real objects <?php namespace Model; class Car { public function __construct(EngineInterface $engine) { $this->engine = $engine; } public function run() { $this->engine->start(); $this->engine->accelerate(10); } public function getActualSpeed() { return $this->engine->getSpeed(); } } <?php namespace TestsModel; class CarTest { public function setUp() { $this->testedObject = new Car( new Engine() ); } public function testRun() { $this->testedObject->run(); $this->assertSame( 10, $this->testedObject->getActualSpeed() ); } …. }
  • 6. The new aproach – pros and cons Pros: • writing tests are much faster • changing class Engine, we don’t need to change also class CarTest • there is possibility that we will find not tested functionality (forgotten or skiped) in class Engine Cons: • when class Engine fail, the CarTest will also fail (but fixing class Engine will fix also CarTest)
  • 7. What we should mock? • We should mock classes that cross the border of business logic layer, for example: – Repositories (data access layer) – File managers (file system layer) – Connectors (facebook, twitter, google oauth)
  • 8. The magic of real objects <?php namespace MyAppTestsRepository; class UsersArrayRepository implement UsersRepositoryInterface { public function __construct(array $users = []) { $this->container = $users; } public function delete(User $user) { foreach($this->container as $key => $elem) { if ($elem->getId() === $user->getId()) { unset($this->container[$key]); return true; } } return false; } … }
  • 9. How to mock <?php namespace MyAppService; class UsersCrud { public function __construct( UsersRepositoryInterface $usersRepository ) { $this->usersRepository = $usersRepository; } public function delete($userId) { $user = $this->usersRepository->find($userId); if (!$user) { throw new UserNotFoundException(); } return $this->usersRepository->delete($user); } } <?php namespace MyAppTestsService; class UsersCrud Test { public function setUp() { $this->testedObject = new UsersCrud ( new UsersArrayRepository( 12 => new User() ) ); } public function testDelete_WhenSuccess() { $result = $this->testedObject->delete(12); $this->assertTrue($result); } …. }
  • 10. Summary • changing name of method „delete” to „deleteOnlyDeacitivatedUser” in UsersRepository will force change in the class „UsersCrud” and „UsersRepositoryTest”, but not in the „UsersCrudTest” • so .. we can do a lot of refactoring without worrying about tests, hundreds of classes which use UsersRepository uwill change automatically by IDE and tests of these classes will still be valid • thx for watching!