SlideShare ist ein Scribd-Unternehmen logo
1 von 32
Downloaden Sie, um offline zu lesen
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.
Benefits 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 confidence
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:

Weitere ähnliche Inhalte

Was ist angesagt?

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
 
Scrum and Test-driven development
Scrum and Test-driven developmentScrum and Test-driven development
Scrum and Test-driven developmenttoteb5
 
Client Side Unit Testing
Client Side Unit TestingClient Side Unit Testing
Client Side Unit Testingcloud chen
 
Code review
Code reviewCode review
Code reviewdqpi
 
#1 unit testing
#1 unit testing#1 unit testing
#1 unit testingeleksdev
 
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
 

Was ist angesagt? (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
 

Andere mochten auch

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
 
Desarrollo Multimedia Android
Desarrollo Multimedia AndroidDesarrollo Multimedia Android
Desarrollo Multimedia AndroidGDG Lima
 

Andere mochten auch (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
 

Ähnlich wie 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
 
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
 
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
 
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
 
Introduction to react native with redux
Introduction to react native with reduxIntroduction to react native with redux
Introduction to react native with reduxMike Melusky
 
Beyond MVC: from Model to Domain
Beyond MVC: from Model to DomainBeyond MVC: from Model to Domain
Beyond MVC: from Model to DomainJeremy Cook
 

Ähnlich wie 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
 
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
 
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
 
Introduction to react native with redux
Introduction to react native with reduxIntroduction to react native with redux
Introduction to react native with redux
 
Beyond MVC: from Model to Domain
Beyond MVC: from Model to DomainBeyond MVC: from Model to Domain
Beyond MVC: from Model to Domain
 

Kürzlich hochgeladen

SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
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
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 

Kürzlich hochgeladen (20)

SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
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
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 

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 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
  • 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. Benefits 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 confidence
  • 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 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)
  • 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)