SlideShare uma empresa Scribd logo
1 de 32
Baixar para ler offline
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 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
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 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)
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:

Mais conteĂșdo relacionado

Mais procurados

DIG1108C Lesson 7 Fall 2014
DIG1108C Lesson 7 Fall 2014DIG1108C Lesson 7 Fall 2014
DIG1108C Lesson 7 Fall 2014David Wolfpaw
 
Quality Assurance Guidelines
Quality Assurance GuidelinesQuality Assurance Guidelines
Quality Assurance GuidelinesTim Stribos
 
iOS Test-Driven Development
iOS Test-Driven DevelopmentiOS Test-Driven Development
iOS Test-Driven DevelopmentPablo 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 UpSourceOleksii Prohonnyi
 
Dependency Injection in iOS
Dependency Injection in iOSDependency Injection in iOS
Dependency Injection in iOSPablo Villar
 
Behavior Driven Development with SpecFlow
Behavior Driven Development with SpecFlowBehavior Driven Development with SpecFlow
Behavior Driven Development with SpecFlowRachid 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 prefixKumaresh 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/AAUInfinIT - InnovationsnetvĂŠrket for it
 
Scrum and Test-driven development
Scrum and Test-driven developmentScrum and Test-driven development
Scrum and Test-driven developmenttoteb5
 
Unit Testing Your Application
Unit Testing Your ApplicationUnit Testing Your Application
Unit Testing Your ApplicationPaladin Web Services
 
Client Side Unit Testing
Client Side Unit TestingClient Side Unit Testing
Client Side Unit Testingcloud chen
 
Code review
Code reviewCode review
Code reviewdqpi
 
Bdd and spec flow
Bdd and spec flowBdd and spec flow
Bdd and spec flowCharles Nurse
 
#1 unit testing
#1 unit testing#1 unit testing
#1 unit testingeleksdev
 
BDD for APIs
BDD for APIsBDD for APIs
BDD for APIsJason 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
 
Behaviour Driven Development with SpecFlow
Behaviour Driven Development with SpecFlowBehaviour Driven Development with SpecFlow
Behaviour Driven Development with SpecFlowPascal Laurin
 
Selenium + Specflow
Selenium + SpecflowSelenium + Specflow
Selenium + Specflowcromwellryan
 

Mais procurados (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
 

Destaque

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 TipsBally 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 Presentationcwhitexs8
 
ĐĄĐ”ĐŒĐžĐœĐ°Ń€ ĐČ ĐłĐŸŃ€ĐŸĐŽĐ” ĐšĐ°ĐŒŃ‹ŃˆĐ»ĐŸĐČĐ”
ĐĄĐ”ĐŒĐžĐœĐ°Ń€ ĐČ ĐłĐŸŃ€ĐŸĐŽĐ” ĐšĐ°ĐŒŃ‹ŃˆĐ»ĐŸĐČĐ”ĐĄĐ”ĐŒĐžĐœĐ°Ń€ ĐČ ĐłĐŸŃ€ĐŸĐŽĐ” ĐšĐ°ĐŒŃ‹ŃˆĐ»ĐŸĐČĐ”
ĐĄĐ”ĐŒĐžĐœĐ°Ń€ ĐČ ĐłĐŸŃ€ĐŸĐŽĐ” ĐšĐ°ĐŒŃ‹ŃˆĐ»ĐŸĐČĐ”rimma_buh
 
IntroducciĂłn al desarrollo con Android
IntroducciĂłn al desarrollo con AndroidIntroducciĂłn al desarrollo con Android
IntroducciĂłn al desarrollo con AndroidGDG Lima
 
Html5 interactivo con easel.js
Html5 interactivo con easel.jsHtml5 interactivo con easel.js
Html5 interactivo con easel.jsGDG Lima
 
Programas de Google devrel para Latam
Programas de Google devrel para LatamProgramas de Google devrel para Latam
Programas de Google devrel para LatamGDG Lima
 
ĐĄĐ”ĐŒĐžĐœĐ°Ń€ ĐČ ĐłĐŸŃ€ĐŸĐŽŃĐșĐŸĐŒ ĐŸĐșŃ€ŃƒĐłĐ” ĐšŃ€Đ°ŃĐœĐŸŃƒŃ„ĐžĐŒŃĐș
ĐĄĐ”ĐŒĐžĐœĐ°Ń€ ĐČ ĐłĐŸŃ€ĐŸĐŽŃĐșĐŸĐŒ ĐŸĐșŃ€ŃƒĐłĐ” ĐšŃ€Đ°ŃĐœĐŸŃƒŃ„ĐžĐŒŃĐșĐĄĐ”ĐŒĐžĐœĐ°Ń€ ĐČ ĐłĐŸŃ€ĐŸĐŽŃĐșĐŸĐŒ ĐŸĐșŃ€ŃƒĐłĐ” ĐšŃ€Đ°ŃĐœĐŸŃƒŃ„ĐžĐŒŃĐș
ĐĄĐ”ĐŒĐžĐœĐ°Ń€ ĐČ ĐłĐŸŃ€ĐŸĐŽŃĐșĐŸĐŒ ĐŸĐșŃ€ŃƒĐłĐ” ĐšŃ€Đ°ŃĐœĐŸŃƒŃ„ĐžĐŒŃĐșrimma_buh
 
Rise 2014 st requier
Rise 2014 st requierRise 2014 st requier
Rise 2014 st requierYSaidali
 
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 androidGDG Lima
 
PresentaciĂłn del programa ADTG
PresentaciĂłn del programa ADTGPresentaciĂłn del programa ADTG
PresentaciĂłn del programa ADTGGDG 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 html5GDG Lima
 
Desarrollo interactivo con Html5
Desarrollo interactivo con Html5Desarrollo interactivo con Html5
Desarrollo interactivo con Html5GDG Lima
 
Taller google Apps Script
Taller google Apps ScriptTaller google Apps Script
Taller google Apps ScriptGDG Lima
 
Google Maps como modelo de negocio
Google Maps como modelo de negocioGoogle Maps como modelo de negocio
Google Maps como modelo de negocioGDG Lima
 
Google Maps como modelo de negocio
Google Maps como modelo de negocioGoogle Maps como modelo de negocio
Google Maps como modelo de negocioGDG Lima
 
Afromix Pump Brochure
Afromix Pump BrochureAfromix Pump Brochure
Afromix Pump BrochureErnest Wermuth
 
Desarrollo Multimedia Android
Desarrollo Multimedia AndroidDesarrollo Multimedia Android
Desarrollo Multimedia AndroidGDG Lima
 

Destaque (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
 

Semelhante a 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 appsPhil Leggetter
 
Introduction to AngularJs
Introduction to AngularJsIntroduction to AngularJs
Introduction to AngularJsmurtazahaveliwala
 
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] 2024Scott Keck-Warren
 
Angular Intermediate
Angular IntermediateAngular Intermediate
Angular IntermediateLinkMe Srl
 
Fed London - January 2015
Fed London - January 2015Fed London - January 2015
Fed London - January 2015Phil 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 - FutureJSPhil Leggetter
 
Professionalizing the Front-end
Professionalizing the Front-endProfessionalizing the Front-end
Professionalizing the Front-endJordi Anguela
 
Dependency Injection in .NET applications
Dependency Injection in .NET applicationsDependency Injection in .NET applications
Dependency Injection in .NET applicationsBabak 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 UIMarcin Grzywaczewski
 
Building scalable applications with angular js
Building scalable applications with angular jsBuilding scalable applications with angular js
Building scalable applications with angular jsAndrew Alpert
 
Ruby For Startups
Ruby For StartupsRuby For Startups
Ruby For StartupsMike Subelsky
 
Mastering the Lightning Framework - Part 1
Mastering the Lightning Framework - Part 1Mastering the Lightning Framework - Part 1
Mastering the Lightning Framework - Part 1Salesforce 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 PrincipleP 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 testingSwapnilNarayan
 
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-phatvuPhat VU
 
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 MizrahiRan Mizrahi
 
Features, Exportables & You
Features, Exportables & YouFeatures, Exportables & You
Features, Exportables & Youjskulski
 
C# Programming: Fundamentals
C# Programming: FundamentalsC# Programming: Fundamentals
C# Programming: FundamentalsMahmoud Abdallah
 

Semelhante a 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
 

Último

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Navi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 

Último (20)

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Navi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 

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)