SlideShare uma empresa Scribd logo
1 de 28
Magento code testability:
Problems and Solutions
Unit testing

One of the main reasons for unit testing is
improvement of code quality.

Unit tests are indicators that instantly show all the
defects of object oriented code.

If code is hard to test – its quality is questionable.
Code flaws in magento detected by unit tests

•   Fat constructors
•   Method complexity
•   Poor OOD (God objects)
•   Law of Demeter violations
•   Global State and Behavior usage
•   …
Fat constructors

Objects that have a lot of behavior in
constructors are hard to test.

You’ve just created the object and it already
created other objects, made some global calls,
changed some global state, etc.
Fat constructors » Solution

Bad: mock all dependencies, create constructor
tests and test all scenarios of constructor.

Good: Move all behavior from constructors.
Leave only data initialization code.
Method Complexity

Unit tests test behavior scenarios. Unit testing
paradigm requires every scenario covered by
separate test.

Each flow control statement adds scenario to
method, so complex methods with many control
structures and protected calls require a lot of
tests and mocks/stubs.
Method Complexity » Solution

Bad: For protected calls – use reflection or
inheritance to test protected behavior in
isolation. Write test per each scenario.

Good: Extract behavior from complex methods
to separate objects that have small
dependencies and are easily testable.
Substitute conditions with polymorphism.
Poor OOD (God objects)

If an object has too many responsibilities there
is a big chance that it will have internal calls
between its public methods.

This creates problems for testing. Developer
has to mock whole object to stub internal public
calls, otherwise he will have test duplication.
Poor OOD (God objects) » Solution

Bad: Mock tested object and stub internal
public calls.

Good: Extract small objects that will have their
own responsibilities to avoid internal public
calls.
Law of Demeter Violations

When tested object receives some context
object that is used only to gain access to third
service object the Law of Demeter is violated.

To test such code one would have to stub
context object only to return service object. If
the chains of calls are long, testing becomes
problematic.
Law of Demeter Violations » Solution

Bad: Create mocks for context objects that will
return themselves on every call except
predefined stubbed calls.

Good: Refactor code to eliminate context
objects. Depend only on objects that are
required for delivering business goals of objects
under test.
Global State And Behavior

Global mutable state is a reason for most bugs. It
is unreliable for code that uses it.

Global state decreases code testability. Code that
uses global state can not be tested in isolation.
Developer must reproduce global environment of a
unit to test it.

Global behavior is a killer of testability. It can not
be mocked or stubbed for testing.
Global State And Behavior in Magento

•   Global arrays
•   Global variables
•   Global factories
•   Mix (state + behavior)
Global State » Arrays


Mage::registry, Mage::register and
Mage::unregister form an interface of
global dynamic service locator simply
wrapping mutable array with global
behavior that restricts access to array
but makes it harder to emulate in testing
environment
Global State » Objects And Variables

•   Mage::app()
•   Mage::getConfig()
•   Mage::get/setIsdeveloperMode()
•   Mage::getIsDownloader()
Global State » Factories

Global factories localize important part of application
behavior – object creation. They eliminate direct
dependencies in code. Which is good.

But instead of implicitly depending on created objects, code
that uses global factories starts to implicitly depend on
them.

Also global factories cannot be substituted in test
environments.
Global State » Factories » Examples

• Mage::getModel()
• Mage::getResourceModel()
• Mage::getControllerInstance()
Global State » Mix (Behavior + State)

These are dangerous in code and are hard to
substitute in tests:

• Mage::getSingleton()
• Mage::helper()
• Mage::getResourceHelper()
Global Behavior and State » Big deal

The big problem with global state and
behavior in Magento is it’s used everywhere.
All the dependencies of objects are pulled
from global state instead of being pushed
(injected) into these objects.

We cannot simply refactor our code to
eliminate global dependencies. We would
have to rewrite magento.
Global Behavior and State » Solution 1

Build “Magento Unit Testing Framework” on top
of PHPUnit, write testing-environment-special
Mage, make it “mockable” and test our code “in
isolation”.

This is an absolutely viable solution that will let
us unit test our code in isolation avoiding
massive refactoring.
The problem

The problem with this solution is the same as
with bad solutions described in previous
sections: It fights the symptom (code non-
testability), not the disease (global state).

And mutable global state and behavior is the
reason of hard to debug type of bugs and
encourages bad practices.
The problem » Bad practices

•   Liar interfaces
•   Law of Demeter violations
•   Deep code dependencies
•   Liskov substitution principle violations
•   Separation of concerns violations
•   Data envy
•   ….
Global State » Solution

• Declare all object dependencies explicitly as
  entries in constructor argument array, and all
  the method-specific arguments as method’s
  parameters instead of pulling them from global
  state. Use object managers instead of global
  arrays when needed.

It will make our interfaces honest. And most code
smells will become visible by only looking at
method signatures. LSP violations will be noted by
interpreter.
Global Behavior » Solution

• If an object must create other objects then it
  must declare dependency on object
  factory, that will be injected into the object.

It will instantly show objects that create too
much.
Global Behavior » Solution

• If an object must create other objects then it
  must declare dependency on object
  factory, that will be injected into the object.

It will instantly show objects that create too
much.
Global usage of Global » Solution

• All the constructors will check presence of
  dependencies in arguments, if an argument
  is not present – it is taken from Global.

It will let us avoid massive refactorings.
Because developer will only have to refactor
the object he tests – not all the code that uses
it. This can be a stage of transforming magento
code to prepare it for DiC.
Sources

• http://misko.hevery.com/
• http://martinfowler.com/articles/injection.html
• Test-Driven Development by Example. Kent
  Beck
Author




         Anton Kril
         Kyiv Dev Folks team
         akril@ebay.com

Mais conteúdo relacionado

Mais procurados

TDD with Visual Studio 2010
TDD with Visual Studio 2010TDD with Visual Studio 2010
TDD with Visual Studio 2010Stefano Paluello
 
Unit testing
Unit testing Unit testing
Unit testing dubbu
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit TestingJoe Tremblay
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@Alex Borsuk
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration TestingDavid Berliner
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseUTC Fire & Security
 
Working Effectively with Legacy Code: Lessons in Practice
Working Effectively with Legacy Code: Lessons in PracticeWorking Effectively with Legacy Code: Lessons in Practice
Working Effectively with Legacy Code: Lessons in PracticeAmar Shah
 
Unit testing legacy code
Unit testing legacy codeUnit testing legacy code
Unit testing legacy codeLars Thorup
 
Intro To Unit and integration Testing
Intro To Unit and integration TestingIntro To Unit and integration Testing
Intro To Unit and integration TestingPaul Churchward
 
Unit testing - the hard parts
Unit testing - the hard partsUnit testing - the hard parts
Unit testing - the hard partsShaun Abram
 
Java Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionJava Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionAlex Su
 
Mock driven development using .NET
Mock driven development using .NETMock driven development using .NET
Mock driven development using .NETPuneet Ghanshani
 
Unit Testing Android Applications
Unit Testing Android ApplicationsUnit Testing Android Applications
Unit Testing Android ApplicationsRody Middelkoop
 
Unit Test + Functional Programming = Love
Unit Test + Functional Programming = LoveUnit Test + Functional Programming = Love
Unit Test + Functional Programming = LoveAlvaro Videla
 
Unit Testing Done Right
Unit Testing Done RightUnit Testing Done Right
Unit Testing Done RightBrian Fenton
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit testEugenio Lentini
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated TestingLee Englestone
 

Mais procurados (20)

TDD with Visual Studio 2010
TDD with Visual Studio 2010TDD with Visual Studio 2010
TDD with Visual Studio 2010
 
Unit testing
Unit testing Unit testing
Unit testing
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration Testing
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + Eclipse
 
Working Effectively with Legacy Code: Lessons in Practice
Working Effectively with Legacy Code: Lessons in PracticeWorking Effectively with Legacy Code: Lessons in Practice
Working Effectively with Legacy Code: Lessons in Practice
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Unit testing legacy code
Unit testing legacy codeUnit testing legacy code
Unit testing legacy code
 
Intro To Unit and integration Testing
Intro To Unit and integration TestingIntro To Unit and integration Testing
Intro To Unit and integration Testing
 
Unit testing - the hard parts
Unit testing - the hard partsUnit testing - the hard parts
Unit testing - the hard parts
 
Java Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionJava Unit Test and Coverage Introduction
Java Unit Test and Coverage Introduction
 
Mock driven development using .NET
Mock driven development using .NETMock driven development using .NET
Mock driven development using .NET
 
Unit Testing Android Applications
Unit Testing Android ApplicationsUnit Testing Android Applications
Unit Testing Android Applications
 
Unit Test + Functional Programming = Love
Unit Test + Functional Programming = LoveUnit Test + Functional Programming = Love
Unit Test + Functional Programming = Love
 
Unit Testing Done Right
Unit Testing Done RightUnit Testing Done Right
Unit Testing Done Right
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit test
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated Testing
 
UNIT TESTING
UNIT TESTINGUNIT TESTING
UNIT TESTING
 

Destaque

Online Localised Content Development (for the African region)
Online Localised Content Development (for the African region)Online Localised Content Development (for the African region)
Online Localised Content Development (for the African region)Duksh Koonjoobeeharry
 
EuroChem Annual Report 2011
EuroChem Annual Report 2011EuroChem Annual Report 2011
EuroChem Annual Report 2011EuroChem
 
Segurtasun informatikoa1
Segurtasun informatikoa1Segurtasun informatikoa1
Segurtasun informatikoa1Krisba
 
Technical paper on Enhansed fertilizers U+AS and U+S Page 103 116 Sandvik - s...
Technical paper on Enhansed fertilizers U+AS and U+S Page 103 116 Sandvik - s...Technical paper on Enhansed fertilizers U+AS and U+S Page 103 116 Sandvik - s...
Technical paper on Enhansed fertilizers U+AS and U+S Page 103 116 Sandvik - s...KVVKSwamy
 
Segurtasun informatikoa1
Segurtasun informatikoa1Segurtasun informatikoa1
Segurtasun informatikoa1Krisba
 
U+AS and U+S Sulphur enhansed fertilizers in Nitrogen
U+AS and U+S Sulphur enhansed fertilizers in Nitrogen U+AS and U+S Sulphur enhansed fertilizers in Nitrogen
U+AS and U+S Sulphur enhansed fertilizers in Nitrogen KVVKSwamy
 
Data tao sql server consultancy services
Data tao sql server consultancy servicesData tao sql server consultancy services
Data tao sql server consultancy servicesDataTao
 
Salim google powerpoint
Salim google powerpointSalim google powerpoint
Salim google powerpointsn022600
 
Nitrogen syngas 2011
Nitrogen syngas 2011Nitrogen syngas 2011
Nitrogen syngas 2011KVVKSwamy
 
Recreational noise exposure and its effects on adolescents
Recreational noise exposure and its effects on adolescentsRecreational noise exposure and its effects on adolescents
Recreational noise exposure and its effects on adolescentspamelaucl
 
Magento Dependency Injection
Magento Dependency InjectionMagento Dependency Injection
Magento Dependency InjectionAnton Kril
 
2012 05 EuroChem Intro
2012 05 EuroChem Intro2012 05 EuroChem Intro
2012 05 EuroChem IntroEuroChem
 

Destaque (16)

Online Localised Content Development (for the African region)
Online Localised Content Development (for the African region)Online Localised Content Development (for the African region)
Online Localised Content Development (for the African region)
 
Культура пачынаецца з цябе вынік
Культура пачынаецца з цябе вынікКультура пачынаецца з цябе вынік
Культура пачынаецца з цябе вынік
 
EuroChem Annual Report 2011
EuroChem Annual Report 2011EuroChem Annual Report 2011
EuroChem Annual Report 2011
 
Segurtasun informatikoa1
Segurtasun informatikoa1Segurtasun informatikoa1
Segurtasun informatikoa1
 
Technical paper on Enhansed fertilizers U+AS and U+S Page 103 116 Sandvik - s...
Technical paper on Enhansed fertilizers U+AS and U+S Page 103 116 Sandvik - s...Technical paper on Enhansed fertilizers U+AS and U+S Page 103 116 Sandvik - s...
Technical paper on Enhansed fertilizers U+AS and U+S Page 103 116 Sandvik - s...
 
Segurtasun informatikoa1
Segurtasun informatikoa1Segurtasun informatikoa1
Segurtasun informatikoa1
 
U+AS and U+S Sulphur enhansed fertilizers in Nitrogen
U+AS and U+S Sulphur enhansed fertilizers in Nitrogen U+AS and U+S Sulphur enhansed fertilizers in Nitrogen
U+AS and U+S Sulphur enhansed fertilizers in Nitrogen
 
Data tao sql server consultancy services
Data tao sql server consultancy servicesData tao sql server consultancy services
Data tao sql server consultancy services
 
Salim google powerpoint
Salim google powerpointSalim google powerpoint
Salim google powerpoint
 
Nitrogen syngas 2011
Nitrogen syngas 2011Nitrogen syngas 2011
Nitrogen syngas 2011
 
Program finantat de perfectionare a cadrelor didactice de religie
Program finantat de perfectionare a cadrelor didactice de religieProgram finantat de perfectionare a cadrelor didactice de religie
Program finantat de perfectionare a cadrelor didactice de religie
 
Recreational noise exposure and its effects on adolescents
Recreational noise exposure and its effects on adolescentsRecreational noise exposure and its effects on adolescents
Recreational noise exposure and its effects on adolescents
 
Magento Dependency Injection
Magento Dependency InjectionMagento Dependency Injection
Magento Dependency Injection
 
Neurosciences of spiritual life. Some results regarding the effect of meditat...
Neurosciences of spiritual life. Some results regarding the effect of meditat...Neurosciences of spiritual life. Some results regarding the effect of meditat...
Neurosciences of spiritual life. Some results regarding the effect of meditat...
 
2012 05 EuroChem Intro
2012 05 EuroChem Intro2012 05 EuroChem Intro
2012 05 EuroChem Intro
 
культура пачынаецца з цябе
культура пачынаецца з цябекультура пачынаецца з цябе
культура пачынаецца з цябе
 

Semelhante a Magento Code Testability Problems and Solutions

Agile principles and practices
Agile principles and practicesAgile principles and practices
Agile principles and practicesVipin Jose
 
MongoDB World 2018: Tutorial - MongoDB Meets Chaos Monkey
MongoDB World 2018: Tutorial - MongoDB Meets Chaos MonkeyMongoDB World 2018: Tutorial - MongoDB Meets Chaos Monkey
MongoDB World 2018: Tutorial - MongoDB Meets Chaos MonkeyMongoDB
 
Play with Testing on Android - Gilang Ramadhan (Academy Content Writer at Dic...
Play with Testing on Android - Gilang Ramadhan (Academy Content Writer at Dic...Play with Testing on Android - Gilang Ramadhan (Academy Content Writer at Dic...
Play with Testing on Android - Gilang Ramadhan (Academy Content Writer at Dic...DicodingEvent
 
Unit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - KenyaUnit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - KenyaErick M'bwana
 
Microsoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable CodeMicrosoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable CodeAleksandar Bozinovski
 
[AnDevCon 2016] Mutation Testing for Android
[AnDevCon 2016] Mutation Testing for Android[AnDevCon 2016] Mutation Testing for Android
[AnDevCon 2016] Mutation Testing for AndroidHazem Saleh
 
Test driven development
Test driven developmentTest driven development
Test driven developmentnamkha87
 
Testing the Untestable
Testing the UntestableTesting the Untestable
Testing the UntestableMark Baker
 
A minimal Django testing styleguide
A minimal Django testing styleguideA minimal Django testing styleguide
A minimal Django testing styleguideJosephZammit17
 
Battle of The Mocking Frameworks
Battle of The Mocking FrameworksBattle of The Mocking Frameworks
Battle of The Mocking FrameworksDror Helper
 
Mockito 2.x Migration - Droidcon UK 2018
Mockito 2.x Migration - Droidcon UK 2018Mockito 2.x Migration - Droidcon UK 2018
Mockito 2.x Migration - Droidcon UK 2018Hazem Saleh
 
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
 
A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)Thierry Gayet
 
谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testabilitydrewz lin
 
Building React Applications with Redux
Building React Applications with ReduxBuilding React Applications with Redux
Building React Applications with ReduxFITC
 

Semelhante a Magento Code Testability Problems and Solutions (20)

Agile principles and practices
Agile principles and practicesAgile principles and practices
Agile principles and practices
 
MongoDB World 2018: Tutorial - MongoDB Meets Chaos Monkey
MongoDB World 2018: Tutorial - MongoDB Meets Chaos MonkeyMongoDB World 2018: Tutorial - MongoDB Meets Chaos Monkey
MongoDB World 2018: Tutorial - MongoDB Meets Chaos Monkey
 
Unit testing basic
Unit testing basicUnit testing basic
Unit testing basic
 
Play with Testing on Android - Gilang Ramadhan (Academy Content Writer at Dic...
Play with Testing on Android - Gilang Ramadhan (Academy Content Writer at Dic...Play with Testing on Android - Gilang Ramadhan (Academy Content Writer at Dic...
Play with Testing on Android - Gilang Ramadhan (Academy Content Writer at Dic...
 
Unit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - KenyaUnit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - Kenya
 
Microsoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable CodeMicrosoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable Code
 
Unit Tests with Microsoft Fakes
Unit Tests with Microsoft FakesUnit Tests with Microsoft Fakes
Unit Tests with Microsoft Fakes
 
[AnDevCon 2016] Mutation Testing for Android
[AnDevCon 2016] Mutation Testing for Android[AnDevCon 2016] Mutation Testing for Android
[AnDevCon 2016] Mutation Testing for Android
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Unit testing - An introduction
Unit testing - An introductionUnit testing - An introduction
Unit testing - An introduction
 
Testing the Untestable
Testing the UntestableTesting the Untestable
Testing the Untestable
 
A minimal Django testing styleguide
A minimal Django testing styleguideA minimal Django testing styleguide
A minimal Django testing styleguide
 
Battle of The Mocking Frameworks
Battle of The Mocking FrameworksBattle of The Mocking Frameworks
Battle of The Mocking Frameworks
 
Mockito 2.x Migration - Droidcon UK 2018
Mockito 2.x Migration - Droidcon UK 2018Mockito 2.x Migration - Droidcon UK 2018
Mockito 2.x Migration - Droidcon UK 2018
 
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
 
Unit Testing in Swift
Unit Testing in SwiftUnit Testing in Swift
Unit Testing in Swift
 
Testing Angular
Testing AngularTesting Angular
Testing Angular
 
A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)
 
谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability
 
Building React Applications with Redux
Building React Applications with ReduxBuilding React Applications with Redux
Building React Applications with Redux
 

Último

Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 

Último (20)

Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 

Magento Code Testability Problems and Solutions

  • 2. Unit testing One of the main reasons for unit testing is improvement of code quality. Unit tests are indicators that instantly show all the defects of object oriented code. If code is hard to test – its quality is questionable.
  • 3. Code flaws in magento detected by unit tests • Fat constructors • Method complexity • Poor OOD (God objects) • Law of Demeter violations • Global State and Behavior usage • …
  • 4. Fat constructors Objects that have a lot of behavior in constructors are hard to test. You’ve just created the object and it already created other objects, made some global calls, changed some global state, etc.
  • 5. Fat constructors » Solution Bad: mock all dependencies, create constructor tests and test all scenarios of constructor. Good: Move all behavior from constructors. Leave only data initialization code.
  • 6. Method Complexity Unit tests test behavior scenarios. Unit testing paradigm requires every scenario covered by separate test. Each flow control statement adds scenario to method, so complex methods with many control structures and protected calls require a lot of tests and mocks/stubs.
  • 7. Method Complexity » Solution Bad: For protected calls – use reflection or inheritance to test protected behavior in isolation. Write test per each scenario. Good: Extract behavior from complex methods to separate objects that have small dependencies and are easily testable. Substitute conditions with polymorphism.
  • 8. Poor OOD (God objects) If an object has too many responsibilities there is a big chance that it will have internal calls between its public methods. This creates problems for testing. Developer has to mock whole object to stub internal public calls, otherwise he will have test duplication.
  • 9. Poor OOD (God objects) » Solution Bad: Mock tested object and stub internal public calls. Good: Extract small objects that will have their own responsibilities to avoid internal public calls.
  • 10. Law of Demeter Violations When tested object receives some context object that is used only to gain access to third service object the Law of Demeter is violated. To test such code one would have to stub context object only to return service object. If the chains of calls are long, testing becomes problematic.
  • 11. Law of Demeter Violations » Solution Bad: Create mocks for context objects that will return themselves on every call except predefined stubbed calls. Good: Refactor code to eliminate context objects. Depend only on objects that are required for delivering business goals of objects under test.
  • 12. Global State And Behavior Global mutable state is a reason for most bugs. It is unreliable for code that uses it. Global state decreases code testability. Code that uses global state can not be tested in isolation. Developer must reproduce global environment of a unit to test it. Global behavior is a killer of testability. It can not be mocked or stubbed for testing.
  • 13. Global State And Behavior in Magento • Global arrays • Global variables • Global factories • Mix (state + behavior)
  • 14. Global State » Arrays Mage::registry, Mage::register and Mage::unregister form an interface of global dynamic service locator simply wrapping mutable array with global behavior that restricts access to array but makes it harder to emulate in testing environment
  • 15. Global State » Objects And Variables • Mage::app() • Mage::getConfig() • Mage::get/setIsdeveloperMode() • Mage::getIsDownloader()
  • 16. Global State » Factories Global factories localize important part of application behavior – object creation. They eliminate direct dependencies in code. Which is good. But instead of implicitly depending on created objects, code that uses global factories starts to implicitly depend on them. Also global factories cannot be substituted in test environments.
  • 17. Global State » Factories » Examples • Mage::getModel() • Mage::getResourceModel() • Mage::getControllerInstance()
  • 18. Global State » Mix (Behavior + State) These are dangerous in code and are hard to substitute in tests: • Mage::getSingleton() • Mage::helper() • Mage::getResourceHelper()
  • 19. Global Behavior and State » Big deal The big problem with global state and behavior in Magento is it’s used everywhere. All the dependencies of objects are pulled from global state instead of being pushed (injected) into these objects. We cannot simply refactor our code to eliminate global dependencies. We would have to rewrite magento.
  • 20. Global Behavior and State » Solution 1 Build “Magento Unit Testing Framework” on top of PHPUnit, write testing-environment-special Mage, make it “mockable” and test our code “in isolation”. This is an absolutely viable solution that will let us unit test our code in isolation avoiding massive refactoring.
  • 21. The problem The problem with this solution is the same as with bad solutions described in previous sections: It fights the symptom (code non- testability), not the disease (global state). And mutable global state and behavior is the reason of hard to debug type of bugs and encourages bad practices.
  • 22. The problem » Bad practices • Liar interfaces • Law of Demeter violations • Deep code dependencies • Liskov substitution principle violations • Separation of concerns violations • Data envy • ….
  • 23. Global State » Solution • Declare all object dependencies explicitly as entries in constructor argument array, and all the method-specific arguments as method’s parameters instead of pulling them from global state. Use object managers instead of global arrays when needed. It will make our interfaces honest. And most code smells will become visible by only looking at method signatures. LSP violations will be noted by interpreter.
  • 24. Global Behavior » Solution • If an object must create other objects then it must declare dependency on object factory, that will be injected into the object. It will instantly show objects that create too much.
  • 25. Global Behavior » Solution • If an object must create other objects then it must declare dependency on object factory, that will be injected into the object. It will instantly show objects that create too much.
  • 26. Global usage of Global » Solution • All the constructors will check presence of dependencies in arguments, if an argument is not present – it is taken from Global. It will let us avoid massive refactorings. Because developer will only have to refactor the object he tests – not all the code that uses it. This can be a stage of transforming magento code to prepare it for DiC.
  • 28. Author Anton Kril Kyiv Dev Folks team akril@ebay.com