SlideShare une entreprise Scribd logo
1  sur  15
Télécharger pour lire hors ligne
Make your SW
components testable

Li-Wei Cheng
Outline
•   Problem ?
•   What's IoC ?
•   Method to make your software components
    testable
Problem ? (1/3)


                    /// pseudo code for CheckAuthentication
                    /// input: string id
                    /// input: string password
                    /// output: true --> if pass the checking
                    ///         false --> else fail the checking

                  Validation depends on Class AccountDAO
                    /// get the password's hash result from DAO
                    AccountDAO dao = new AccountDao();
                    String passwordHashFromDAO =
                                            dao.getPasswordHash(id);

                  Validation depends on Class Hash
                    /// get the id's hash result from Hash
                    Hash hash = new Hash();
                    String hashResult = hash.getHashResult(password);

                    /// check the result
                    return passwordHashFromDAO.equals(hashResult);
Problem ? (2/3)
                  It violates the OCP (Open Closed Principle)
                  If we want to mock AccountDAO & Hash,
                  we must modify the code in class of Validation.


                    /// pseudo code for CheckAuthentication
                    /// input: string id
                    /// input: string password
                    /// output: true --> if pass the checking
                    ///         false --> else fail the checking


                    /// get the password's hash result from DAO
                    AccountDAO dao = new AccountDao();
                    String passwordHashFromDAO =
                                            dao.getPasswordHash(id);


                    /// get the id's hash result from Hash
                    Hash hash = new Hash();
                    String hashResult = hash.getHashResult(password);

                    /// check the result
                    return passwordHashFromDAO.equals(hashResult);
Problem ? (3/3)
                               Now, you can upgrade your AccountDAO &
                               Hash without modifying the class of Validation.
                               (If you just want to test, mock it.)


這個把初始化動作,由原本目標物件內,轉移到目標物件之外,     /// pseudo code for CheckAuthentication
稱作「控制反轉
   控制反轉」,也就是IoC。
   控制反轉                          /// input: string id
                                 /// input: string password
                                 /// output: true --> if pass the checking
                                 ///         false --> else fail the checking


                                 /// get the password's hash result from DAO
這個把依賴的物件,透過目標物件公開建構式,交給外         AccountDAO dao = new AccountDao();
部來決定,稱作「依賴注入
        依賴注入」,也就是DI。
        依賴注入                     String passwordHashFromDAO =
                                                         mDao.getPasswordHash(id);


                                 /// get the id's hash result from Hash
                                 Hash hash = new Hash();
                                 String hashResult = mHash.getHashResult(password);

                                 /// check the result
                                 return passwordHashFromDAO.equals(hashResult);
Definition for IoC & DI
•   Inversion of Control [IoC] (from wiki)
    o   An object-oriented programming practice where the
        object coupling is bound at run time by an assembler
        object and it typically not known at compile time
        using static analysis.

    o   Usually used in Unit Test to do the isolation test.

•   Dependency Injection [DI] (from wiki)
    o   A software design pattern that allows a choice of
        component to be made at run-time rather than
        compile time.
Method to make your SW testable (1)

•   Constructor
•   Public Setter
•   Pass Arguments
•   Inheritance
Method to make your SW testable (2)

•   Constructor [used in the previous slides]
•   Public Setter
•   Pass Arguments
•   Inheritance
Method to make your SW testable (3)

•   Constructor
•   Public Setter
•   Pass Arguments
•   Inheritance
Method to make your SW testable (4)
                  Set the dependency object via public setter




                    /// pseudo code for CheckAuthentication
                    /// input: string id
                    /// input: string password
                    /// output: true --> if pass the checking
                    ///         false --> else fail the checking


                    /// get the password's hash result from DAO
                    AccountDAO dao = new AccountDao();
                    String passwordHashFromDAO =
                                            mDao.getPasswordHash(id);


                    /// get the id's hash result from Hash
                    Hash hash = new Hash();
                    String hashResult = mHash.getHashResult(password);

                    /// check the result
                    return passwordHashFromDAO.equals(hashResult);
Method to make your SW testable (5)

•   Constructor
•   Public Setter
•   Pass Arguments
•   Inheritance
Method to make your SW testable (6)


                   /// pseudo code for CheckAuthentication
                   /// input: string id
                   /// input: string password
                   /// input: Hash hash
                   /// input: AccountDAO dao
                   /// output: true --> if pass the checking
                   ///         false --> else fail the checking


                   /// get the password's hash result from DAO
                   AccountDAO dao = new AccountDao();
                   String passwordHashFromDAO =
                                           dao.getPasswordHash(id);


                   /// get the id's hash result from Hash
                   Hash hash = new Hash();
                   String hashResult = hash.getHashResult(password);

                   /// check the result
                   return passwordHashFromDAO.equals(hashResult);
Method to make your SW testable (7)

•   Constructor
•   Public Setter
•   Pass Arguments
•   Inheritance
Method to make your SW testable (8)
                  Use the subclass to do the UT.
                  Override the getter to mock objects.



                    /// pseudo code for CheckAuthentication
                    /// input: string id
                    /// input: string password
                    /// output: true --> if pass the checking
                    ///         false --> else fail the checking


                    /// get the password's hash result from DAO
                    AccountDAO dao = getAccountDAO();
                    String passwordHashFromDAO =
                                            dao.getPasswordHash(id);


                    /// get the id's hash result from Hash
                    Hash hash = getHash();
                    String hashResult = hash.getHashResult(password);

                    /// check the result
                    return passwordHashFromDAO.equals(hashResult);
Compare these ways
 Method Name                 Cons                             Pros
                 由建構式傳入相依介面的實體物件,是一個              與原本直接相依的程式碼相比較,目標物件的
Constructor      很通用的方式。因此在結合許多常見的DI              相依物件因此暴露出來,交由外部決定,而喪
                 framework,不需要在額外處理。              失了一點封裝的意味。

                 同樣的,public property也是常見的         最常見的情況,就是使用目標物件時,相依介
Public Setter    dependency injection points,所以   面應有其對應執行個體,但卻因為使用端沒有
                 也有許多DI framework支援。另外則是不         設定public property,導致使用方法時出
                 需要對建構式進行改變,或增加新的建構式              現NullReferenceException,這種情況也
                 。對過去已經存在的legacy code的影響,         怪不了使用端,因為使用端極有可能本就不瞭
                 會比建構式的方式小一點點(但幾乎沒有太              解這個方法中,有哪些相依物件
                 大差異)

                 不必再擔心要先初始化哪些property,或           最大的問題,在於方法簽章上的不穩定性。當
Pass Arguments   呼叫哪一個建構式。當要呼叫某一個方法,              需求異動,該方法需要額外相依於其他物件時
                 其相依的物件,就是得透過參數來給定。基              ,方法簽章可能會被迫改變。而方法簽章是物
                 本上也不太需要擔心使用上造成困擾或迷惑              件導向設計上,最需要穩定的條件之一。以物
                                                  件導向、介面導向設計來說,當多型物件方法
                                                  簽章不一致時,向來是個大問題。

                 這個方式最大的好處,是完全不影響外部使              這是為了測試,且legacy code所使用的方式
Inheritance      用物件的方式。僅透過protected與             ,而不是良好的物件導向設計的方式。IoC的
                 virtual來對繼承鏈開放擴充的功能,並且           用意在於介面導向與擴充點的彈性,所以當可
                 透過這樣的方式,就使得原本直接相依而導              測試之後,倘若重構影響範圍不大,建議讀者
                 致無法測試的問題,獲得解套。                   朋友還是要將物件改相依於介面,透過IoC的
                                                  方式來設計物件。

Contenu connexe

Tendances

HotSpot template interpreter memos
HotSpot template interpreter memosHotSpot template interpreter memos
HotSpot template interpreter memosytoshima
 
JVM code reading -- C2
JVM code reading -- C2JVM code reading -- C2
JVM code reading -- C2ytoshima
 
Jim Manico: Developer Top 10 Core Controls, web application security @ OWASP ...
Jim Manico: Developer Top 10 Core Controls, web application security @ OWASP ...Jim Manico: Developer Top 10 Core Controls, web application security @ OWASP ...
Jim Manico: Developer Top 10 Core Controls, web application security @ OWASP ...Xlator
 
Eight simple rules to writing secure PHP programs
Eight simple rules to writing secure PHP programsEight simple rules to writing secure PHP programs
Eight simple rules to writing secure PHP programsAleksandr Yampolskiy
 
ORM2Pwn: Exploiting injections in Hibernate ORM
ORM2Pwn: Exploiting injections in Hibernate ORMORM2Pwn: Exploiting injections in Hibernate ORM
ORM2Pwn: Exploiting injections in Hibernate ORMMikhail Egorov
 
Créer et gérer une scratch org avec Visual Studio Code
Créer et gérer une scratch org avec Visual Studio CodeCréer et gérer une scratch org avec Visual Studio Code
Créer et gérer une scratch org avec Visual Studio CodeThierry TROUIN ☁
 
Сканирование с использованием бэкслэша: подключаем интуицию
Сканирование с использованием бэкслэша: подключаем интуициюСканирование с использованием бэкслэша: подключаем интуицию
Сканирование с использованием бэкслэша: подключаем интуициюPositive Hack Days
 
Proposed PHP function: is_literal()
Proposed PHP function: is_literal()Proposed PHP function: is_literal()
Proposed PHP function: is_literal()Craig Francis
 
How to Develop a Secure Web Application and Stay in Mind? (PHDays 3)
How to Develop a Secure Web Application and Stay in Mind? (PHDays 3)How to Develop a Secure Web Application and Stay in Mind? (PHDays 3)
How to Develop a Secure Web Application and Stay in Mind? (PHDays 3)Vladimir Kochetkov
 
Tk2323 lecture 9 api json
Tk2323 lecture 9   api jsonTk2323 lecture 9   api json
Tk2323 lecture 9 api jsonMengChun Lam
 
PHP security audits
PHP security auditsPHP security audits
PHP security auditsDamien Seguy
 
OWASP Top 10 - DrupalCon Amsterdam 2019
OWASP Top 10 - DrupalCon Amsterdam 2019OWASP Top 10 - DrupalCon Amsterdam 2019
OWASP Top 10 - DrupalCon Amsterdam 2019Ayesh Karunaratne
 
Dealing with Legacy PHP Applications
Dealing with Legacy PHP ApplicationsDealing with Legacy PHP Applications
Dealing with Legacy PHP ApplicationsClinton Dreisbach
 
Web Security Mistakes: Trusting The Client
Web Security Mistakes: Trusting The ClientWeb Security Mistakes: Trusting The Client
Web Security Mistakes: Trusting The Clientgrutz
 
Comment utiliser Visual Studio Code pour travailler avec une scratch Org
Comment utiliser Visual Studio Code pour travailler avec une scratch OrgComment utiliser Visual Studio Code pour travailler avec une scratch Org
Comment utiliser Visual Studio Code pour travailler avec une scratch OrgThierry TROUIN ☁
 

Tendances (20)

HotSpot template interpreter memos
HotSpot template interpreter memosHotSpot template interpreter memos
HotSpot template interpreter memos
 
JVM code reading -- C2
JVM code reading -- C2JVM code reading -- C2
JVM code reading -- C2
 
Jim Manico: Developer Top 10 Core Controls, web application security @ OWASP ...
Jim Manico: Developer Top 10 Core Controls, web application security @ OWASP ...Jim Manico: Developer Top 10 Core Controls, web application security @ OWASP ...
Jim Manico: Developer Top 10 Core Controls, web application security @ OWASP ...
 
Eight simple rules to writing secure PHP programs
Eight simple rules to writing secure PHP programsEight simple rules to writing secure PHP programs
Eight simple rules to writing secure PHP programs
 
ORM2Pwn: Exploiting injections in Hibernate ORM
ORM2Pwn: Exploiting injections in Hibernate ORMORM2Pwn: Exploiting injections in Hibernate ORM
ORM2Pwn: Exploiting injections in Hibernate ORM
 
Créer et gérer une scratch org avec Visual Studio Code
Créer et gérer une scratch org avec Visual Studio CodeCréer et gérer une scratch org avec Visual Studio Code
Créer et gérer une scratch org avec Visual Studio Code
 
Сканирование с использованием бэкслэша: подключаем интуицию
Сканирование с использованием бэкслэша: подключаем интуициюСканирование с использованием бэкслэша: подключаем интуицию
Сканирование с использованием бэкслэша: подключаем интуицию
 
Proposed PHP function: is_literal()
Proposed PHP function: is_literal()Proposed PHP function: is_literal()
Proposed PHP function: is_literal()
 
How to Develop a Secure Web Application and Stay in Mind? (PHDays 3)
How to Develop a Secure Web Application and Stay in Mind? (PHDays 3)How to Develop a Secure Web Application and Stay in Mind? (PHDays 3)
How to Develop a Secure Web Application and Stay in Mind? (PHDays 3)
 
PHP Secure Programming
PHP Secure ProgrammingPHP Secure Programming
PHP Secure Programming
 
Tk2323 lecture 9 api json
Tk2323 lecture 9   api jsonTk2323 lecture 9   api json
Tk2323 lecture 9 api json
 
PHP security audits
PHP security auditsPHP security audits
PHP security audits
 
Php Security
Php SecurityPhp Security
Php Security
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
OWASP Top 10 - DrupalCon Amsterdam 2019
OWASP Top 10 - DrupalCon Amsterdam 2019OWASP Top 10 - DrupalCon Amsterdam 2019
OWASP Top 10 - DrupalCon Amsterdam 2019
 
Dealing with Legacy PHP Applications
Dealing with Legacy PHP ApplicationsDealing with Legacy PHP Applications
Dealing with Legacy PHP Applications
 
PHP Security
PHP SecurityPHP Security
PHP Security
 
Web Security Mistakes: Trusting The Client
Web Security Mistakes: Trusting The ClientWeb Security Mistakes: Trusting The Client
Web Security Mistakes: Trusting The Client
 
Metaprogramming in ES6
Metaprogramming in ES6Metaprogramming in ES6
Metaprogramming in ES6
 
Comment utiliser Visual Studio Code pour travailler avec une scratch Org
Comment utiliser Visual Studio Code pour travailler avec une scratch OrgComment utiliser Visual Studio Code pour travailler avec une scratch Org
Comment utiliser Visual Studio Code pour travailler avec une scratch Org
 

En vedette

Designing for Testability
Designing for TestabilityDesigning for Testability
Designing for TestabilityJason Dobry
 
Introduction to AndroidMock
Introduction to AndroidMockIntroduction to AndroidMock
Introduction to AndroidMockLi-Wei Cheng
 
Applied MyEclipse and JUnit to do Hibernate Code Gen and Testing
Applied MyEclipse and JUnit to do Hibernate Code Gen and TestingApplied MyEclipse and JUnit to do Hibernate Code Gen and Testing
Applied MyEclipse and JUnit to do Hibernate Code Gen and TestingGuo Albert
 
OO design principle
OO design principleOO design principle
OO design principleLi-Wei Cheng
 
What's software testing
What's software testingWhat's software testing
What's software testingLi-Wei Cheng
 
Testability: Factors and Strategy
Testability: Factors and StrategyTestability: Factors and Strategy
Testability: Factors and StrategyBob Binder
 
Testing and Testable Code
Testing and Testable CodeTesting and Testable Code
Testing and Testable CodePawel Szulc
 
Software Design for Testability
Software Design for TestabilitySoftware Design for Testability
Software Design for Testabilityamr0mt
 
May the feature be with you
May the feature be with youMay the feature be with you
May the feature be with youShoun Ichida
 
Unit testing in android
Unit testing in androidUnit testing in android
Unit testing in androidLi-Wei Cheng
 

En vedette (14)

Designing for Testability
Designing for TestabilityDesigning for Testability
Designing for Testability
 
Introduction to AndroidMock
Introduction to AndroidMockIntroduction to AndroidMock
Introduction to AndroidMock
 
Applied MyEclipse and JUnit to do Hibernate Code Gen and Testing
Applied MyEclipse and JUnit to do Hibernate Code Gen and TestingApplied MyEclipse and JUnit to do Hibernate Code Gen and Testing
Applied MyEclipse and JUnit to do Hibernate Code Gen and Testing
 
GN 2014 TLs
GN 2014 TLsGN 2014 TLs
GN 2014 TLs
 
OO design principle
OO design principleOO design principle
OO design principle
 
What's software testing
What's software testingWhat's software testing
What's software testing
 
Testability: Factors and Strategy
Testability: Factors and StrategyTestability: Factors and Strategy
Testability: Factors and Strategy
 
Testing and Testable Code
Testing and Testable CodeTesting and Testable Code
Testing and Testable Code
 
Software Design for Testability
Software Design for TestabilitySoftware Design for Testability
Software Design for Testability
 
Designing Testable Software
Designing Testable SoftwareDesigning Testable Software
Designing Testable Software
 
May the feature be with you
May the feature be with youMay the feature be with you
May the feature be with you
 
JUnit
JUnitJUnit
JUnit
 
UML knowledge
UML knowledgeUML knowledge
UML knowledge
 
Unit testing in android
Unit testing in androidUnit testing in android
Unit testing in android
 

Similaire à Make Your SW Component Testable

02 banking trojans-thomassiebert
02 banking trojans-thomassiebert02 banking trojans-thomassiebert
02 banking trojans-thomassiebertgeeksec80
 
DEF CON 27 - ALVARO MUNOZ / OLEKSANDR MIROSH - sso wars the token menace
DEF CON 27 - ALVARO MUNOZ / OLEKSANDR MIROSH - sso wars the token menaceDEF CON 27 - ALVARO MUNOZ / OLEKSANDR MIROSH - sso wars the token menace
DEF CON 27 - ALVARO MUNOZ / OLEKSANDR MIROSH - sso wars the token menaceFelipe Prado
 
OWASP San Diego Training Presentation
OWASP San Diego Training PresentationOWASP San Diego Training Presentation
OWASP San Diego Training Presentationowaspsd
 
Third Party Auth in WebObjects
Third Party Auth in WebObjectsThird Party Auth in WebObjects
Third Party Auth in WebObjectsWO Community
 
Static Analysis in IDEA
Static Analysis in IDEAStatic Analysis in IDEA
Static Analysis in IDEAHamletDRC
 
Super simple application security with Apache Shiro
Super simple application security with Apache ShiroSuper simple application security with Apache Shiro
Super simple application security with Apache ShiroMarakana Inc.
 
Preventing Data Breaches: How to Tighten Your Security Stance
Preventing Data Breaches: How to Tighten Your Security StancePreventing Data Breaches: How to Tighten Your Security Stance
Preventing Data Breaches: How to Tighten Your Security StanceSara Goodison
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Michelangelo van Dam
 
Get Soaked - An In Depth Look At PHP Streams
Get Soaked - An In Depth Look At PHP StreamsGet Soaked - An In Depth Look At PHP Streams
Get Soaked - An In Depth Look At PHP StreamsDavey Shafik
 
OWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxOWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxFernandoVizer
 
Top Ten Web Defenses - DefCamp 2012
Top Ten Web Defenses  - DefCamp 2012Top Ten Web Defenses  - DefCamp 2012
Top Ten Web Defenses - DefCamp 2012DefCamp
 
OWASP Secure Coding
OWASP Secure CodingOWASP Secure Coding
OWASP Secure Codingbilcorry
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Michelangelo van Dam
 
Cross Site Scripting (XSS) Defense with Java
Cross Site Scripting (XSS) Defense with JavaCross Site Scripting (XSS) Defense with Java
Cross Site Scripting (XSS) Defense with JavaJim Manico
 
Hybrid Analyzer for Web Application Security (HAWAS) by Lavakumar Kuppan
Hybrid Analyzer for Web Application Security (HAWAS) by Lavakumar KuppanHybrid Analyzer for Web Application Security (HAWAS) by Lavakumar Kuppan
Hybrid Analyzer for Web Application Security (HAWAS) by Lavakumar KuppanClubHack
 
501 - PHP MYSQL.pdf
501 - PHP MYSQL.pdf501 - PHP MYSQL.pdf
501 - PHP MYSQL.pdfAkashGohil10
 

Similaire à Make Your SW Component Testable (20)

02 banking trojans-thomassiebert
02 banking trojans-thomassiebert02 banking trojans-thomassiebert
02 banking trojans-thomassiebert
 
DEF CON 27 - ALVARO MUNOZ / OLEKSANDR MIROSH - sso wars the token menace
DEF CON 27 - ALVARO MUNOZ / OLEKSANDR MIROSH - sso wars the token menaceDEF CON 27 - ALVARO MUNOZ / OLEKSANDR MIROSH - sso wars the token menace
DEF CON 27 - ALVARO MUNOZ / OLEKSANDR MIROSH - sso wars the token menace
 
OWASP San Diego Training Presentation
OWASP San Diego Training PresentationOWASP San Diego Training Presentation
OWASP San Diego Training Presentation
 
secure php
secure phpsecure php
secure php
 
Third Party Auth in WebObjects
Third Party Auth in WebObjectsThird Party Auth in WebObjects
Third Party Auth in WebObjects
 
Static Analysis in IDEA
Static Analysis in IDEAStatic Analysis in IDEA
Static Analysis in IDEA
 
Test doubles
Test doublesTest doubles
Test doubles
 
Super simple application security with Apache Shiro
Super simple application security with Apache ShiroSuper simple application security with Apache Shiro
Super simple application security with Apache Shiro
 
Preventing Data Breaches: How to Tighten Your Security Stance
Preventing Data Breaches: How to Tighten Your Security StancePreventing Data Breaches: How to Tighten Your Security Stance
Preventing Data Breaches: How to Tighten Your Security Stance
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012
 
Get Soaked - An In Depth Look At PHP Streams
Get Soaked - An In Depth Look At PHP StreamsGet Soaked - An In Depth Look At PHP Streams
Get Soaked - An In Depth Look At PHP Streams
 
OWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxOWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptx
 
CDI @javaonehyderabad
CDI @javaonehyderabadCDI @javaonehyderabad
CDI @javaonehyderabad
 
Top Ten Web Defenses - DefCamp 2012
Top Ten Web Defenses  - DefCamp 2012Top Ten Web Defenses  - DefCamp 2012
Top Ten Web Defenses - DefCamp 2012
 
OWASP Secure Coding
OWASP Secure CodingOWASP Secure Coding
OWASP Secure Coding
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
 
Cross Site Scripting (XSS) Defense with Java
Cross Site Scripting (XSS) Defense with JavaCross Site Scripting (XSS) Defense with Java
Cross Site Scripting (XSS) Defense with Java
 
Hybrid Analyzer for Web Application Security (HAWAS) by Lavakumar Kuppan
Hybrid Analyzer for Web Application Security (HAWAS) by Lavakumar KuppanHybrid Analyzer for Web Application Security (HAWAS) by Lavakumar Kuppan
Hybrid Analyzer for Web Application Security (HAWAS) by Lavakumar Kuppan
 
Web security
Web securityWeb security
Web security
 
501 - PHP MYSQL.pdf
501 - PHP MYSQL.pdf501 - PHP MYSQL.pdf
501 - PHP MYSQL.pdf
 

Dernier

The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
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
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
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
 
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
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
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
 
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
 
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
 
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
 

Dernier (20)

The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
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
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
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
 
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
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
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
 
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
 
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?
 

Make Your SW Component Testable

  • 1. Make your SW components testable Li-Wei Cheng
  • 2. Outline • Problem ? • What's IoC ? • Method to make your software components testable
  • 3. Problem ? (1/3) /// pseudo code for CheckAuthentication /// input: string id /// input: string password /// output: true --> if pass the checking /// false --> else fail the checking Validation depends on Class AccountDAO /// get the password's hash result from DAO AccountDAO dao = new AccountDao(); String passwordHashFromDAO = dao.getPasswordHash(id); Validation depends on Class Hash /// get the id's hash result from Hash Hash hash = new Hash(); String hashResult = hash.getHashResult(password); /// check the result return passwordHashFromDAO.equals(hashResult);
  • 4. Problem ? (2/3) It violates the OCP (Open Closed Principle) If we want to mock AccountDAO & Hash, we must modify the code in class of Validation. /// pseudo code for CheckAuthentication /// input: string id /// input: string password /// output: true --> if pass the checking /// false --> else fail the checking /// get the password's hash result from DAO AccountDAO dao = new AccountDao(); String passwordHashFromDAO = dao.getPasswordHash(id); /// get the id's hash result from Hash Hash hash = new Hash(); String hashResult = hash.getHashResult(password); /// check the result return passwordHashFromDAO.equals(hashResult);
  • 5. Problem ? (3/3) Now, you can upgrade your AccountDAO & Hash without modifying the class of Validation. (If you just want to test, mock it.) 這個把初始化動作,由原本目標物件內,轉移到目標物件之外, /// pseudo code for CheckAuthentication 稱作「控制反轉 控制反轉」,也就是IoC。 控制反轉 /// input: string id /// input: string password /// output: true --> if pass the checking /// false --> else fail the checking /// get the password's hash result from DAO 這個把依賴的物件,透過目標物件公開建構式,交給外 AccountDAO dao = new AccountDao(); 部來決定,稱作「依賴注入 依賴注入」,也就是DI。 依賴注入 String passwordHashFromDAO = mDao.getPasswordHash(id); /// get the id's hash result from Hash Hash hash = new Hash(); String hashResult = mHash.getHashResult(password); /// check the result return passwordHashFromDAO.equals(hashResult);
  • 6. Definition for IoC & DI • Inversion of Control [IoC] (from wiki) o An object-oriented programming practice where the object coupling is bound at run time by an assembler object and it typically not known at compile time using static analysis. o Usually used in Unit Test to do the isolation test. • Dependency Injection [DI] (from wiki) o A software design pattern that allows a choice of component to be made at run-time rather than compile time.
  • 7. Method to make your SW testable (1) • Constructor • Public Setter • Pass Arguments • Inheritance
  • 8. Method to make your SW testable (2) • Constructor [used in the previous slides] • Public Setter • Pass Arguments • Inheritance
  • 9. Method to make your SW testable (3) • Constructor • Public Setter • Pass Arguments • Inheritance
  • 10. Method to make your SW testable (4) Set the dependency object via public setter /// pseudo code for CheckAuthentication /// input: string id /// input: string password /// output: true --> if pass the checking /// false --> else fail the checking /// get the password's hash result from DAO AccountDAO dao = new AccountDao(); String passwordHashFromDAO = mDao.getPasswordHash(id); /// get the id's hash result from Hash Hash hash = new Hash(); String hashResult = mHash.getHashResult(password); /// check the result return passwordHashFromDAO.equals(hashResult);
  • 11. Method to make your SW testable (5) • Constructor • Public Setter • Pass Arguments • Inheritance
  • 12. Method to make your SW testable (6) /// pseudo code for CheckAuthentication /// input: string id /// input: string password /// input: Hash hash /// input: AccountDAO dao /// output: true --> if pass the checking /// false --> else fail the checking /// get the password's hash result from DAO AccountDAO dao = new AccountDao(); String passwordHashFromDAO = dao.getPasswordHash(id); /// get the id's hash result from Hash Hash hash = new Hash(); String hashResult = hash.getHashResult(password); /// check the result return passwordHashFromDAO.equals(hashResult);
  • 13. Method to make your SW testable (7) • Constructor • Public Setter • Pass Arguments • Inheritance
  • 14. Method to make your SW testable (8) Use the subclass to do the UT. Override the getter to mock objects. /// pseudo code for CheckAuthentication /// input: string id /// input: string password /// output: true --> if pass the checking /// false --> else fail the checking /// get the password's hash result from DAO AccountDAO dao = getAccountDAO(); String passwordHashFromDAO = dao.getPasswordHash(id); /// get the id's hash result from Hash Hash hash = getHash(); String hashResult = hash.getHashResult(password); /// check the result return passwordHashFromDAO.equals(hashResult);
  • 15. Compare these ways Method Name Cons Pros 由建構式傳入相依介面的實體物件,是一個 與原本直接相依的程式碼相比較,目標物件的 Constructor 很通用的方式。因此在結合許多常見的DI 相依物件因此暴露出來,交由外部決定,而喪 framework,不需要在額外處理。 失了一點封裝的意味。 同樣的,public property也是常見的 最常見的情況,就是使用目標物件時,相依介 Public Setter dependency injection points,所以 面應有其對應執行個體,但卻因為使用端沒有 也有許多DI framework支援。另外則是不 設定public property,導致使用方法時出 需要對建構式進行改變,或增加新的建構式 現NullReferenceException,這種情況也 。對過去已經存在的legacy code的影響, 怪不了使用端,因為使用端極有可能本就不瞭 會比建構式的方式小一點點(但幾乎沒有太 解這個方法中,有哪些相依物件 大差異) 不必再擔心要先初始化哪些property,或 最大的問題,在於方法簽章上的不穩定性。當 Pass Arguments 呼叫哪一個建構式。當要呼叫某一個方法, 需求異動,該方法需要額外相依於其他物件時 其相依的物件,就是得透過參數來給定。基 ,方法簽章可能會被迫改變。而方法簽章是物 本上也不太需要擔心使用上造成困擾或迷惑 件導向設計上,最需要穩定的條件之一。以物 件導向、介面導向設計來說,當多型物件方法 簽章不一致時,向來是個大問題。 這個方式最大的好處,是完全不影響外部使 這是為了測試,且legacy code所使用的方式 Inheritance 用物件的方式。僅透過protected與 ,而不是良好的物件導向設計的方式。IoC的 virtual來對繼承鏈開放擴充的功能,並且 用意在於介面導向與擴充點的彈性,所以當可 透過這樣的方式,就使得原本直接相依而導 測試之後,倘若重構影響範圍不大,建議讀者 致無法測試的問題,獲得解套。 朋友還是要將物件改相依於介面,透過IoC的 方式來設計物件。