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
 
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
 
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
 
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
 
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 "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?"
 
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

BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 

Recently uploaded (20)

BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 

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!