SlideShare a Scribd company logo
Writing Testable Code
“Testable”?
• When we write object oriented code, we write individual units
(classes / objects and their methods)
• Testable code is code that we can easily write automated unit tests
for
• Testable code is of a better quality, more isolated and written to
comply with SOLID* principles
• This is what we will work towards
* more on this later
Types of Automated Tests
• Unit tests - a test that verifies the behaviour an individual method,
function or class / object
• Functional tests - tests that ensure the application does what it is
supposed to without caring about how it achieves it
• Behavioural testing - verifies that the software behaves as the user
would expect it to - usually involves automating the browser
Why are tests so important?
!4
• When we write code, how do we know it behaves as we expect?
• If we write some code that performs the addition of two numbers,
how do we know it handles negative values correctly?
• We can manually test our code, but this isn’t good enough
• As programmers we should always look to automate our processes
to reduce repetition, tests are no exception to this rule.
Benets of Automated Testing
• Tests prove that our code works as we expect
• Writing our tests makes us think about edge cases, and what we
expect from our code in those cases
• Protects against regressions
• Let’s us know that something is broken before we ship a release
• Reduces the amount of manual testing required
Refactoring
Automated tests allow us to refactor with condence
Tests + Continuous Integration
• We currently use Jenkins as our continuous integration server
(https://jenkins.dt.awsripple.com)
• Jenkins “builds” our project and let’s us know if it’s broken
• If we have tests that cover every business rule in our application, we
will know the code is broken before we ship a release
• Reduces the feedback loop between us and the client
• Improves quality
Thinking About Dependencies
What is a dependency?
• When we write multiple units of code (multiple classes / objects),
they work together to create a working application / website.
• We refer to these units as components
• A component might rely on another component in order to work
• If component X relies on component Y, we say that component X has
a dependency on component Y
Mandatory Dependencies
• A mandatory dependency is something that the component cannot
function without
• For example, we could say that a smart phone has a mandatory
dependency on an operating system
• When a dependency is mandatory, we inject it into the constructor of
the dependent object
Mandatory Dependencies
<?php!
! !
class SamsungGalaxy extends Phone!
{!
! private $operatingSystem;!
!
! public function __construct(OperatingSystem $android)!
! {!
! ! $this->operatingSystem = $android;!
! }!
}
Optional Dependencies
• An optional dependency is something that the component can
function without
• For example, we could say that the smart phone optionally depends
on a USB connection to a computer
• When a dependency is optional, we inject it via a setter method
Optional Dependencies
<?php!
! !
class SamsungGalaxy extends Phone!
{!
! private $operatingSystem;!
! private $usbConnection;!
!
! public function __construct(OperatingSystem $android)!
! {!
! ! $this->operatingSystem = $android;!
! }!
!
! public function setUsbConnection(UsbConnection $usbConnection)!
! {!
! ! $this->usbConnection = $usbConnection;!
! }!
}
Optional Dependencies
<?php!
! !
class SamsungGalaxy extends Phone!
{!
! // ...!
!
! public function receiveCall(PhoneCall $call)!
! {!
! ! if (null !== $this->usbConnection) {!
! ! ! $this->usbConnection->haltTransfers();!
! ! }!
! !
! ! $call->answer();!
}!
}
Why are objects dependent on another?
• In object oriented programming, we use objects (created from
classes) to encapsulate functionality
• Each object should do something specific, and do it well
• This is known as Single Responsibility Principle (SRP) - the S in the
SOLID principles (we will cover more of these over the next few
sessions)
Example of SRP
• Earlier we talked about injecting an OperatingSystem object into
the SamsungGalaxy phone object
• This is a separation of responsibility, because the phone is not
implementing the logic of the operating system
• If we had all of our logic of the OperatingSystem object inside the
SamsungGalaxy object, it would be doing too much and would
violate SRP
• This would allow us to test our OperatingSystem as a unit of code
Real Code Example
Code Example: User Manager
• Let’s say we have a bunch of users in an application
• We have an object in our application that is responsible for
managing users, the UserManager
• The UserManager is where we create, update and delete users in
the database
• We should create multiple components to ease the UserManager’s
job
Code Example: User Manager
• Our manager needs to:
• Persist / update users to the database
• Hash passwords for users
• Delete users from the database
Code Example: User Manager
<?php!
! !
class UserManager extends Phone!
{!
! private $db;!
! private $passwordHasher!
!
! public function __construct(!
! ! ConnectionInterface $db,!
! ! PasswordHasherInterface $passwordHasher!
! ) {!
! ! $this->db = $db;!
! ! $this->passwordHasher = $passwordHasher;!
}!
}
Code Example: User Manager
• With separate components, we can write tests for each of them in
isolation
• We can also swap our dependencies out easily if we choose to do so,
our UserManager won’t care
• When writing our tests for the UserManager we can mock* any
dependencies (e.g. the DatabaseConnectionInterface) which
means we don’t need to test with real dependencies
• Mocking allows us to test units of code on their own, rather than doing
integration testing (hence the term “Unit Testing”)
*more on mocking in a future session
Step 2: Managing Dependencies
Objects With Dependencies
• Separating concerns into different objects means we have to create
multiple objects
• This can get unwieldy when we have several dependencies
• This also means that our code has to be aware of all the different
dependencies that an object relies on….
Example: Inline Instantiation
<?php!
! !
class UserController!
{!
! public function createAction()!
! {!
! ! $passwordHasher = new BcryptPasswordHasher();!
! ! $connection = new DatabaseConnection($options);!
!
! ! $userManager = new UserManager($connection, $passwordHasher);!
! }!
}
This is a nightmare…
Dependency Injection Containers
(DIC)
DIC: Managing Dependencies
• In our UserController example, we needed to have knowledge
of the dependencies that the UserManager required
• What if we wanted to change the BcryptPasswordHasher to
PbkPasswordHasher?
• We would have to change code all over our application (wherever
we have used the UserManager)
DIC: Managing Dependencies
• A DIC will manage our objects (sometimes referred to as services)
and their dependencies for us
• If we want to get our UserManager from a DIC, we just need to ask
for it - we don’t care what else the UserManager depends on
• This allows us to scale the complexity of our object dependencies
without complicating our code
Pimple: A simple DIC
<?php!
! !
class Container extends Pimple!
{!
! public function __construct()!
! {!
! ! $this[‘user_manager’] = function() {!
! ! ! $passwordHasher = new BcryptPasswordHasher();!
! ! ! $connection = new DatabaseConnection();!
!
! ! ! return new UserManager($passwordHasher, $connection);!
! ! };!
! }!
}
Pimple: A simple DIC
<?php!
! !
class Container extends Pimple!
{!
! public function __construct()!
! {!
! ! $this[‘password_hasher’] = function() {!
! ! ! return new BcryptPasswordHasher();!
! ! };!
!
! ! $this[‘db’] = function() {!
! ! ! return new DatabaseConnection();!
! ! };!
!
! ! $this[‘user_manager’] = function($c) {!
! ! ! return new UserManager($c[‘password_hasher’], $c[‘db’]);!
! ! };!
}!
}
Even better…
Using the DIC
<?php!
! !
class UserController!
{!
! public function createAction()!
! {!
! ! $container = $this->getContainer(); // fetch the container!
! ! $userManager = $container[‘user_manager’];!
! }!
}
• Our controller action is now much simpler and has no knowledge of
the UserManager’s dependencies.
What Next?
• Pimple can be implemented on any legacy project, just install it
using composer
• We can start separating concerns when writing our code, always
think about SRP
• Read about the SOLID principles and understand them (ask for help
if needed)
Writing Unit Tests
Next Session:

More Related Content

What's hot

DIG1108C Lesson 7 Fall 2014
DIG1108C Lesson 7 Fall 2014DIG1108C Lesson 7 Fall 2014
DIG1108C Lesson 7 Fall 2014
David Wolfpaw
 
Quality Assurance Guidelines
Quality Assurance GuidelinesQuality Assurance Guidelines
Quality Assurance Guidelines
Tim Stribos
 
iOS Test-Driven Development
iOS Test-Driven DevelopmentiOS Test-Driven Development
iOS Test-Driven Development
Pablo Villar
 
Test Driven iOS Development (TDD)
Test Driven iOS Development (TDD)Test Driven iOS Development (TDD)
Test Driven iOS Development (TDD)
Babul Mirdha
 
Code review process with JetBrains UpSource
Code review process with JetBrains UpSourceCode review process with JetBrains UpSource
Code review process with JetBrains UpSource
Oleksii Prohonnyi
 
Dependency Injection in iOS
Dependency Injection in iOSDependency Injection in iOS
Dependency Injection in iOS
Pablo Villar
 
Behavior Driven Development with SpecFlow
Behavior Driven Development with SpecFlowBehavior Driven Development with SpecFlow
Behavior Driven Development with SpecFlow
Rachid Kherrazi
 
Git branching policy and review comment's prefix
Git branching policy and review comment's prefixGit branching policy and review comment's prefix
Git branching policy and review comment's prefix
Kumaresh Chandra Baruri
 
Test Automation and Keyword-driven testing af Brian Nielsen, CISS/AAU
Test Automation and Keyword-driven testing af Brian Nielsen, CISS/AAUTest Automation and Keyword-driven testing af Brian Nielsen, CISS/AAU
Test Automation and Keyword-driven testing af Brian Nielsen, CISS/AAU
InfinIT - InnovationsnetvĂŚrket for it
 
Scrum and Test-driven development
Scrum and Test-driven developmentScrum and Test-driven development
Scrum and Test-driven development
toteb5
 
Unit Testing Your Application
Unit Testing Your ApplicationUnit Testing Your Application
Unit Testing Your Application
Paladin Web Services
 
Client Side Unit Testing
Client Side Unit TestingClient Side Unit Testing
Client Side Unit Testing
cloud chen
 
Code review
Code reviewCode review
Code review
dqpi
 
Bdd and spec flow
Bdd and spec flowBdd and spec flow
Bdd and spec flow
Charles Nurse
 
#1 unit testing
#1 unit testing#1 unit testing
#1 unit testing
eleksdev
 
BDD for APIs
BDD for APIsBDD for APIs
BDD for APIs
Jason Harmon
 
Functional & Performance Test Automation with CI
Functional & Performance Test Automation with CI Functional & Performance Test Automation with CI
Functional & Performance Test Automation with CI
Leonard Fingerman
 
Agile test practices
Agile test practicesAgile test practices
Agile test practices
Leonard Fingerman
 
Behaviour Driven Development with SpecFlow
Behaviour Driven Development with SpecFlowBehaviour Driven Development with SpecFlow
Behaviour Driven Development with SpecFlow
Pascal Laurin
 
Selenium + Specflow
Selenium + SpecflowSelenium + Specflow
Selenium + Specflow
cromwellryan
 

What's hot (20)

DIG1108C Lesson 7 Fall 2014
DIG1108C Lesson 7 Fall 2014DIG1108C Lesson 7 Fall 2014
DIG1108C Lesson 7 Fall 2014
 
Quality Assurance Guidelines
Quality Assurance GuidelinesQuality Assurance Guidelines
Quality Assurance Guidelines
 
iOS Test-Driven Development
iOS Test-Driven DevelopmentiOS Test-Driven Development
iOS Test-Driven Development
 
Test Driven iOS Development (TDD)
Test Driven iOS Development (TDD)Test Driven iOS Development (TDD)
Test Driven iOS Development (TDD)
 
Code review process with JetBrains UpSource
Code review process with JetBrains UpSourceCode review process with JetBrains UpSource
Code review process with JetBrains UpSource
 
Dependency Injection in iOS
Dependency Injection in iOSDependency Injection in iOS
Dependency Injection in iOS
 
Behavior Driven Development with SpecFlow
Behavior Driven Development with SpecFlowBehavior Driven Development with SpecFlow
Behavior Driven Development with SpecFlow
 
Git branching policy and review comment's prefix
Git branching policy and review comment's prefixGit branching policy and review comment's prefix
Git branching policy and review comment's prefix
 
Test Automation and Keyword-driven testing af Brian Nielsen, CISS/AAU
Test Automation and Keyword-driven testing af Brian Nielsen, CISS/AAUTest Automation and Keyword-driven testing af Brian Nielsen, CISS/AAU
Test Automation and Keyword-driven testing af Brian Nielsen, CISS/AAU
 
Scrum and Test-driven development
Scrum and Test-driven developmentScrum and Test-driven development
Scrum and Test-driven development
 
Unit Testing Your Application
Unit Testing Your ApplicationUnit Testing Your Application
Unit Testing Your Application
 
Client Side Unit Testing
Client Side Unit TestingClient Side Unit Testing
Client Side Unit Testing
 
Code review
Code reviewCode review
Code review
 
Bdd and spec flow
Bdd and spec flowBdd and spec flow
Bdd and spec flow
 
#1 unit testing
#1 unit testing#1 unit testing
#1 unit testing
 
BDD for APIs
BDD for APIsBDD for APIs
BDD for APIs
 
Functional & Performance Test Automation with CI
Functional & Performance Test Automation with CI Functional & Performance Test Automation with CI
Functional & Performance Test Automation with CI
 
Agile test practices
Agile test practicesAgile test practices
Agile test practices
 
Behaviour Driven Development with SpecFlow
Behaviour Driven Development with SpecFlowBehaviour Driven Development with SpecFlow
Behaviour Driven Development with SpecFlow
 
Selenium + Specflow
Selenium + SpecflowSelenium + Specflow
Selenium + Specflow
 

Viewers also liked

Get beach body with Bally Chohan Fitness Tips
Get beach body with Bally Chohan Fitness TipsGet beach body with Bally Chohan Fitness Tips
Get beach body with Bally Chohan Fitness Tips
Bally Chohan Fitness Tips
 
White Jr. Calvin - Ignite Slides Presentation
White Jr. Calvin - Ignite Slides PresentationWhite Jr. Calvin - Ignite Slides Presentation
White Jr. Calvin - Ignite Slides Presentation
cwhitexs8
 
Семинар в городе Камышлове
Семинар в городе КамышловеСеминар в городе Камышлове
Семинар в городе Камышловеrimma_buh
 
IntroducciĂłn al desarrollo con Android
IntroducciĂłn al desarrollo con AndroidIntroducciĂłn al desarrollo con Android
IntroducciĂłn al desarrollo con Android
GDG Lima
 
Html5 interactivo con easel.js
Html5 interactivo con easel.jsHtml5 interactivo con easel.js
Html5 interactivo con easel.js
GDG Lima
 
Programas de Google devrel para Latam
Programas de Google devrel para LatamProgramas de Google devrel para Latam
Programas de Google devrel para Latam
GDG Lima
 
Семинар в городском округе Красноуфимск
Семинар в городском округе КрасноуфимскСеминар в городском округе Красноуфимск
Семинар в городском округе Красноуфимскrimma_buh
 
Rise 2014 st requier
Rise 2014 st requierRise 2014 st requier
Rise 2014 st requier
YSaidali
 
IntroducciĂłn al desarrollo para mĂłviles en android
IntroducciĂłn al desarrollo para mĂłviles en androidIntroducciĂłn al desarrollo para mĂłviles en android
IntroducciĂłn al desarrollo para mĂłviles en android
GDG Lima
 
Conventions of dps
Conventions of dpsConventions of dps
Conventions of dps
tiffanyyyjones101
 
PresentaciĂłn del programa ADTG
PresentaciĂłn del programa ADTGPresentaciĂłn del programa ADTG
PresentaciĂłn del programa ADTG
GDG Lima
 
Adobe Air para desarrollo mĂłvil
Adobe Air para desarrollo mĂłvilAdobe Air para desarrollo mĂłvil
Adobe Air para desarrollo mĂłvilGDG Lima
 
Desarrollo interactivo con html5
Desarrollo interactivo con html5Desarrollo interactivo con html5
Desarrollo interactivo con html5
GDG Lima
 
Desarrollo interactivo con Html5
Desarrollo interactivo con Html5Desarrollo interactivo con Html5
Desarrollo interactivo con Html5
GDG Lima
 
Taller google Apps Script
Taller google Apps ScriptTaller google Apps Script
Taller google Apps Script
GDG Lima
 
Google Maps como modelo de negocio
Google Maps como modelo de negocioGoogle Maps como modelo de negocio
Google Maps como modelo de negocio
GDG Lima
 
Google Maps como modelo de negocio
Google Maps como modelo de negocioGoogle Maps como modelo de negocio
Google Maps como modelo de negocio
GDG Lima
 
Afromix Pump Brochure
Afromix Pump BrochureAfromix Pump Brochure
Afromix Pump Brochure
Ernest Wermuth
 
Desarrollo Multimedia Android
Desarrollo Multimedia AndroidDesarrollo Multimedia Android
Desarrollo Multimedia Android
GDG Lima
 

Viewers also liked (20)

Get beach body with Bally Chohan Fitness Tips
Get beach body with Bally Chohan Fitness TipsGet beach body with Bally Chohan Fitness Tips
Get beach body with Bally Chohan Fitness Tips
 
White Jr. Calvin - Ignite Slides Presentation
White Jr. Calvin - Ignite Slides PresentationWhite Jr. Calvin - Ignite Slides Presentation
White Jr. Calvin - Ignite Slides Presentation
 
Семинар в городе Камышлове
Семинар в городе КамышловеСеминар в городе Камышлове
Семинар в городе Камышлове
 
IntroducciĂłn al desarrollo con Android
IntroducciĂłn al desarrollo con AndroidIntroducciĂłn al desarrollo con Android
IntroducciĂłn al desarrollo con Android
 
Html5 interactivo con easel.js
Html5 interactivo con easel.jsHtml5 interactivo con easel.js
Html5 interactivo con easel.js
 
Programas de Google devrel para Latam
Programas de Google devrel para LatamProgramas de Google devrel para Latam
Programas de Google devrel para Latam
 
Семинар в городском округе Красноуфимск
Семинар в городском округе КрасноуфимскСеминар в городском округе Красноуфимск
Семинар в городском округе Красноуфимск
 
Rise 2014 st requier
Rise 2014 st requierRise 2014 st requier
Rise 2014 st requier
 
IntroducciĂłn al desarrollo para mĂłviles en android
IntroducciĂłn al desarrollo para mĂłviles en androidIntroducciĂłn al desarrollo para mĂłviles en android
IntroducciĂłn al desarrollo para mĂłviles en android
 
Prosthetiki demo presentation
Prosthetiki demo presentationProsthetiki demo presentation
Prosthetiki demo presentation
 
Conventions of dps
Conventions of dpsConventions of dps
Conventions of dps
 
PresentaciĂłn del programa ADTG
PresentaciĂłn del programa ADTGPresentaciĂłn del programa ADTG
PresentaciĂłn del programa ADTG
 
Adobe Air para desarrollo mĂłvil
Adobe Air para desarrollo mĂłvilAdobe Air para desarrollo mĂłvil
Adobe Air para desarrollo mĂłvil
 
Desarrollo interactivo con html5
Desarrollo interactivo con html5Desarrollo interactivo con html5
Desarrollo interactivo con html5
 
Desarrollo interactivo con Html5
Desarrollo interactivo con Html5Desarrollo interactivo con Html5
Desarrollo interactivo con Html5
 
Taller google Apps Script
Taller google Apps ScriptTaller google Apps Script
Taller google Apps Script
 
Google Maps como modelo de negocio
Google Maps como modelo de negocioGoogle Maps como modelo de negocio
Google Maps como modelo de negocio
 
Google Maps como modelo de negocio
Google Maps como modelo de negocioGoogle Maps como modelo de negocio
Google Maps como modelo de negocio
 
Afromix Pump Brochure
Afromix Pump BrochureAfromix Pump Brochure
Afromix Pump Brochure
 
Desarrollo Multimedia Android
Desarrollo Multimedia AndroidDesarrollo Multimedia Android
Desarrollo Multimedia Android
 

Similar to Writing Testable Code

Patterns and practices for building enterprise-scale HTML5 apps
Patterns and practices for building enterprise-scale HTML5 appsPatterns and practices for building enterprise-scale HTML5 apps
Patterns and practices for building enterprise-scale HTML5 apps
Phil Leggetter
 
Introduction to AngularJs
Introduction to AngularJsIntroduction to AngularJs
Introduction to AngularJs
murtazahaveliwala
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
Scott Keck-Warren
 
Angular Intermediate
Angular IntermediateAngular Intermediate
Angular Intermediate
LinkMe Srl
 
Fed London - January 2015
Fed London - January 2015Fed London - January 2015
Fed London - January 2015
Phil Leggetter
 
How to Build Front-End Web Apps that Scale - FutureJS
How to Build Front-End Web Apps that Scale - FutureJSHow to Build Front-End Web Apps that Scale - FutureJS
How to Build Front-End Web Apps that Scale - FutureJS
Phil Leggetter
 
Professionalizing the Front-end
Professionalizing the Front-endProfessionalizing the Front-end
Professionalizing the Front-end
Jordi Anguela
 
Dependency Injection in .NET applications
Dependency Injection in .NET applicationsDependency Injection in .NET applications
Dependency Injection in .NET applications
Babak Naffas
 
React.js - and how it changed our thinking about UI
React.js - and how it changed our thinking about UIReact.js - and how it changed our thinking about UI
React.js - and how it changed our thinking about UI
Marcin Grzywaczewski
 
Building scalable applications with angular js
Building scalable applications with angular jsBuilding scalable applications with angular js
Building scalable applications with angular js
Andrew Alpert
 
Ruby For Startups
Ruby For StartupsRuby For Startups
Ruby For Startups
Mike Subelsky
 
Mastering the Lightning Framework - Part 1
Mastering the Lightning Framework - Part 1Mastering the Lightning Framework - Part 1
Mastering the Lightning Framework - Part 1
Salesforce Developers
 
Mock Objects, Design and Dependency Inversion Principle
Mock Objects, Design and Dependency Inversion PrincipleMock Objects, Design and Dependency Inversion Principle
Mock Objects, Design and Dependency Inversion Principle
P Heinonen
 
Slides for Automation Testing or End to End testing
Slides for Automation Testing or End to End testingSlides for Automation Testing or End to End testing
Slides for Automation Testing or End to End testing
SwapnilNarayan
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]
GDSC UofT Mississauga
 
Devday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvuDevday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvu
Phat VU
 
Angular js
Angular jsAngular js
Angular js
Mauro Servienti
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
Features, Exportables & You
Features, Exportables & YouFeatures, Exportables & You
Features, Exportables & You
jskulski
 
C# Programming: Fundamentals
C# Programming: FundamentalsC# Programming: Fundamentals
C# Programming: Fundamentals
Mahmoud Abdallah
 

Similar to Writing Testable Code (20)

Patterns and practices for building enterprise-scale HTML5 apps
Patterns and practices for building enterprise-scale HTML5 appsPatterns and practices for building enterprise-scale HTML5 apps
Patterns and practices for building enterprise-scale HTML5 apps
 
Introduction to AngularJs
Introduction to AngularJsIntroduction to AngularJs
Introduction to AngularJs
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Angular Intermediate
Angular IntermediateAngular Intermediate
Angular Intermediate
 
Fed London - January 2015
Fed London - January 2015Fed London - January 2015
Fed London - January 2015
 
How to Build Front-End Web Apps that Scale - FutureJS
How to Build Front-End Web Apps that Scale - FutureJSHow to Build Front-End Web Apps that Scale - FutureJS
How to Build Front-End Web Apps that Scale - FutureJS
 
Professionalizing the Front-end
Professionalizing the Front-endProfessionalizing the Front-end
Professionalizing the Front-end
 
Dependency Injection in .NET applications
Dependency Injection in .NET applicationsDependency Injection in .NET applications
Dependency Injection in .NET applications
 
React.js - and how it changed our thinking about UI
React.js - and how it changed our thinking about UIReact.js - and how it changed our thinking about UI
React.js - and how it changed our thinking about UI
 
Building scalable applications with angular js
Building scalable applications with angular jsBuilding scalable applications with angular js
Building scalable applications with angular js
 
Ruby For Startups
Ruby For StartupsRuby For Startups
Ruby For Startups
 
Mastering the Lightning Framework - Part 1
Mastering the Lightning Framework - Part 1Mastering the Lightning Framework - Part 1
Mastering the Lightning Framework - Part 1
 
Mock Objects, Design and Dependency Inversion Principle
Mock Objects, Design and Dependency Inversion PrincipleMock Objects, Design and Dependency Inversion Principle
Mock Objects, Design and Dependency Inversion Principle
 
Slides for Automation Testing or End to End testing
Slides for Automation Testing or End to End testingSlides for Automation Testing or End to End testing
Slides for Automation Testing or End to End testing
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]
 
Devday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvuDevday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvu
 
Angular js
Angular jsAngular js
Angular js
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 
Features, Exportables & You
Features, Exportables & YouFeatures, Exportables & You
Features, Exportables & You
 
C# Programming: Fundamentals
C# Programming: FundamentalsC# Programming: Fundamentals
C# Programming: Fundamentals
 

Recently uploaded

Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
Antonios Katsarakis
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
Miro Wengner
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
Javier Junquera
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
Session 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdfSession 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdf
UiPathCommunity
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
Fwdays
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
A Deep Dive into ScyllaDB's Architecture
A Deep Dive into ScyllaDB's ArchitectureA Deep Dive into ScyllaDB's Architecture
A Deep Dive into ScyllaDB's Architecture
ScyllaDB
 
Essentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation ParametersEssentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation Parameters
Safe Software
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 
Mutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented ChatbotsMutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented Chatbots
Pablo GĂłmez Abajo
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
AstuteBusiness
 
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance PanelsNorthern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
Jason Yip
 
Must Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during MigrationMust Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during Migration
Mydbops
 

Recently uploaded (20)

Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
Session 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdfSession 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdf
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
A Deep Dive into ScyllaDB's Architecture
A Deep Dive into ScyllaDB's ArchitectureA Deep Dive into ScyllaDB's Architecture
A Deep Dive into ScyllaDB's Architecture
 
Essentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation ParametersEssentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation Parameters
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 
Mutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented ChatbotsMutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented Chatbots
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
 
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance PanelsNorthern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
 
Must Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during MigrationMust Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during Migration
 

Writing Testable Code

  • 2. “Testable”? • When we write object oriented code, we write individual units (classes / objects and their methods) • Testable code is code that we can easily write automated unit tests for • Testable code is of a better quality, more isolated and written to comply with SOLID* principles • This is what we will work towards * more on this later
  • 3. Types of Automated Tests • Unit tests - a test that veries the behaviour an individual method, function or class / object • Functional tests - tests that ensure the application does what it is supposed to without caring about how it achieves it • Behavioural testing - veries that the software behaves as the user would expect it to - usually involves automating the browser
  • 4. Why are tests so important? !4 • When we write code, how do we know it behaves as we expect? • If we write some code that performs the addition of two numbers, how do we know it handles negative values correctly? • We can manually test our code, but this isn’t good enough • As programmers we should always look to automate our processes to reduce repetition, tests are no exception to this rule.
  • 5. Benets of Automated Testing • Tests prove that our code works as we expect • Writing our tests makes us think about edge cases, and what we expect from our code in those cases • Protects against regressions • Let’s us know that something is broken before we ship a release • Reduces the amount of manual testing required
  • 6. Refactoring Automated tests allow us to refactor with condence
  • 7. Tests + Continuous Integration • We currently use Jenkins as our continuous integration server (https://jenkins.dt.awsripple.com) • Jenkins “builds” our project and let’s us know if it’s broken • If we have tests that cover every business rule in our application, we will know the code is broken before we ship a release • Reduces the feedback loop between us and the client • Improves quality
  • 9. What is a dependency? • When we write multiple units of code (multiple classes / objects), they work together to create a working application / website. • We refer to these units as components • A component might rely on another component in order to work • If component X relies on component Y, we say that component X has a dependency on component Y
  • 10. Mandatory Dependencies • A mandatory dependency is something that the component cannot function without • For example, we could say that a smart phone has a mandatory dependency on an operating system • When a dependency is mandatory, we inject it into the constructor of the dependent object
  • 11. Mandatory Dependencies <?php! ! ! class SamsungGalaxy extends Phone! {! ! private $operatingSystem;! ! ! public function __construct(OperatingSystem $android)! ! {! ! ! $this->operatingSystem = $android;! ! }! }
  • 12. Optional Dependencies • An optional dependency is something that the component can function without • For example, we could say that the smart phone optionally depends on a USB connection to a computer • When a dependency is optional, we inject it via a setter method
  • 13. Optional Dependencies <?php! ! ! class SamsungGalaxy extends Phone! {! ! private $operatingSystem;! ! private $usbConnection;! ! ! public function __construct(OperatingSystem $android)! ! {! ! ! $this->operatingSystem = $android;! ! }! ! ! public function setUsbConnection(UsbConnection $usbConnection)! ! {! ! ! $this->usbConnection = $usbConnection;! ! }! }
  • 14. Optional Dependencies <?php! ! ! class SamsungGalaxy extends Phone! {! ! // ...! ! ! public function receiveCall(PhoneCall $call)! ! {! ! ! if (null !== $this->usbConnection) {! ! ! ! $this->usbConnection->haltTransfers();! ! ! }! ! ! ! ! $call->answer();! }! }
  • 15. Why are objects dependent on another? • In object oriented programming, we use objects (created from classes) to encapsulate functionality • Each object should do something specic, and do it well • This is known as Single Responsibility Principle (SRP) - the S in the SOLID principles (we will cover more of these over the next few sessions)
  • 16. Example of SRP • Earlier we talked about injecting an OperatingSystem object into the SamsungGalaxy phone object • This is a separation of responsibility, because the phone is not implementing the logic of the operating system • If we had all of our logic of the OperatingSystem object inside the SamsungGalaxy object, it would be doing too much and would violate SRP • This would allow us to test our OperatingSystem as a unit of code
  • 18. Code Example: User Manager • Let’s say we have a bunch of users in an application • We have an object in our application that is responsible for managing users, the UserManager • The UserManager is where we create, update and delete users in the database • We should create multiple components to ease the UserManager’s job
  • 19. Code Example: User Manager • Our manager needs to: • Persist / update users to the database • Hash passwords for users • Delete users from the database
  • 20. Code Example: User Manager <?php! ! ! class UserManager extends Phone! {! ! private $db;! ! private $passwordHasher! ! ! public function __construct(! ! ! ConnectionInterface $db,! ! ! PasswordHasherInterface $passwordHasher! ! ) {! ! ! $this->db = $db;! ! ! $this->passwordHasher = $passwordHasher;! }! }
  • 21. Code Example: User Manager • With separate components, we can write tests for each of them in isolation • We can also swap our dependencies out easily if we choose to do so, our UserManager won’t care • When writing our tests for the UserManager we can mock* any dependencies (e.g. the DatabaseConnectionInterface) which means we don’t need to test with real dependencies • Mocking allows us to test units of code on their own, rather than doing integration testing (hence the term “Unit Testing”) *more on mocking in a future session
  • 22. Step 2: Managing Dependencies
  • 23. Objects With Dependencies • Separating concerns into different objects means we have to create multiple objects • This can get unwieldy when we have several dependencies • This also means that our code has to be aware of all the different dependencies that an object relies on….
  • 24. Example: Inline Instantiation <?php! ! ! class UserController! {! ! public function createAction()! ! {! ! ! $passwordHasher = new BcryptPasswordHasher();! ! ! $connection = new DatabaseConnection($options);! ! ! ! $userManager = new UserManager($connection, $passwordHasher);! ! }! } This is a nightmare…
  • 26. DIC: Managing Dependencies • In our UserController example, we needed to have knowledge of the dependencies that the UserManager required • What if we wanted to change the BcryptPasswordHasher to PbkPasswordHasher? • We would have to change code all over our application (wherever we have used the UserManager)
  • 27. DIC: Managing Dependencies • A DIC will manage our objects (sometimes referred to as services) and their dependencies for us • If we want to get our UserManager from a DIC, we just need to ask for it - we don’t care what else the UserManager depends on • This allows us to scale the complexity of our object dependencies without complicating our code
  • 28. Pimple: A simple DIC <?php! ! ! class Container extends Pimple! {! ! public function __construct()! ! {! ! ! $this[‘user_manager’] = function() {! ! ! ! $passwordHasher = new BcryptPasswordHasher();! ! ! ! $connection = new DatabaseConnection();! ! ! ! ! return new UserManager($passwordHasher, $connection);! ! ! };! ! }! }
  • 29. Pimple: A simple DIC <?php! ! ! class Container extends Pimple! {! ! public function __construct()! ! {! ! ! $this[‘password_hasher’] = function() {! ! ! ! return new BcryptPasswordHasher();! ! ! };! ! ! ! $this[‘db’] = function() {! ! ! ! return new DatabaseConnection();! ! ! };! ! ! ! $this[‘user_manager’] = function($c) {! ! ! ! return new UserManager($c[‘password_hasher’], $c[‘db’]);! ! ! };! }! } Even better…
  • 30. Using the DIC <?php! ! ! class UserController! {! ! public function createAction()! ! {! ! ! $container = $this->getContainer(); // fetch the container! ! ! $userManager = $container[‘user_manager’];! ! }! } • Our controller action is now much simpler and has no knowledge of the UserManager’s dependencies.
  • 31. What Next? • Pimple can be implemented on any legacy project, just install it using composer • We can start separating concerns when writing our code, always think about SRP • Read about the SOLID principles and understand them (ask for help if needed)