SlideShare a Scribd company logo
1 of 34
Download to read offline
Unit Test & TDD
Sendo Workshop
Viet Tran - Sendo Software Architect
viettranx@gmail.com
AGENDA
▸ Unit Test: What & Why
▸ Current problems at Sendo and solution
▸ Clean Architecture
▸ TDD - Test Development Driven
▸ Demo: Write Unit Test, the right way
WHAT IS UNIT TEST ?
Unit testing is a software development process in which the
smallest testable parts of an application, called units, are
individually and independently scrutinized for proper
operation.
WHY UNIT TEST ?
▸ Unit tests detect changes that may break a design contract
▸ Standardize: Unit testing improves the quality of code
▸ Unit testing helps reduce the cost of bug fixes
▸ It's fun
EXAMPLE FOR UNIT TEST
func Sum(x int, y int) int {
return x + y
}
func TestSum(t *testing.T) {
total := Sum(5, 5)
expect := 10
assert.Equal(t, 10, total, "should be qual")
}
EXAMPLE FOR UNIT TEST
func Sum(x int, y int) int {
return x + y
}
func TestSum(t *testing.T) {
tables := []struct {
args []int
expect int
}{
{[]int{5,5}, 10},
{[]int{8,9}, 17},
{[]int{1,0}, 1},
}
for _, c := tables {
actual := Sum(c.args[0], c.args[1])
assert.Equal(t, actual, c.expect, "should
be qual")
}
}
LAUNCHING TESTS
$ go test -v
This picks up any files matching packagename_test.go
$ go test -cover
PASS
coverage: 66.67% of statements
CURRENT PROBLEMS AT SENDO
▸ Have no Unit Test, QC have to test manually and full flow.
▸ High tightly coding, every change might break the others.
▸ Huge function body, very hard to maintain.
▸ CI/CD does not support Unit Test checking.
CURRENT PROBLEMS AT SENDO (CONTINUE)
LOGIC 1 LOGIC 2 LOGIC 3 LOGIC ...Huge Function
DBConcrete Objects REST CALL SERVICE CALL
It's very hard to maintain these stuff
Most of problems in software development
can be solved by delegation
HOW DOES DELEGATION WORKS ?
LOGIN CONCRETE LOGIN DB
I know who you are and what exactly you can do
I need to login Just wait until I finish my job
HOW DOES DELEGATION WORKS ? (CONTINUE)
LOGIN CONCRETE LOGIN DB
I don't know who you are but what exactly you can do
I need to login Just call and I will implement it.
DELEGATION / ABSTRACTION
HOW DOES DELEGATION WORKS ? COME TO TESTING
LOGIN TEST MOCK LOGIN DB
Independently testing: Testing without real DB connection
I need to run testing Simulate all cases of login function
DELEGATION / ABSTRACTION
Instead of direct calling, we use delegation
UNIT TEST EXAMPLE: IS IT A GOOD PRACTICE ?
type Thing struct{}
func InsertThing(doc *Thing) error {
session, err := mgo.Dial("localhost")
if err != nil {
return errors.New("Can not connect to db")
}
defer session.Close()
db := session.DB("test")
db.Collection("things").Insert(doc); err != nil {
return errors.New("Can not insert thing")
}
return nil
}
UNIT TEST EXAMPLE: IS IT A GOOD PRACTICE ? (CONT.)
It's bad practice.
WHY ?
type Thing struct{}
func InsertThing(doc *Thing) error {
session, err := mgo.Dial("localhost")
if err != nil {
return errors.New("Can not connect to db")
}
defer session.Close()
db := session.DB("test")
db.Collection("things").Insert(doc); err != nil {
return errors.New("Can not insert thing")
}
return nil
}
UNIT TEST EXAMPLE (CONTINUE)
type Thing struct{}
func InsertThing(doc *Thing) error {
session, err := mgo.Dial("localhost")
if err != nil {
return errors.New("Can not connect to db")
}
defer session.Close()
db := session.DB("test")
db.Collection("things").Insert(doc); err != nil {
return errors.New("Can not insert thing")
}
return nil
}
CONNECT DB
INSERT THING
UNIT TEST EXAMPLE (CONTINUE)
func TestInsertThing(t *testing.T) {
doc := Thing{}
err := InsertThing(&doc)
assert.NotNil(t, err, "should be not nil")
}
A basic Unit Test for InsertThing
UNIT TEST EXAMPLE (COVERAGE)
type Thing struct{}
func InsertThing(doc *Thing) error {
session, err := mgo.Dial("localhost")
if err != nil {
return errors.New("Can not connect to db")
}
defer session.Close()
db := session.DB("test")
db.Collection("things").Insert(doc); err != nil {
return errors.New("Can not insert thing")
}
return nil
}
func TestInsertThing(t *testing.T) {
doc := Thing{}
err := InsertThing(&doc)
assert.NotNil(t, err, "should be not nil")
}
▸ We need a real DB Connection.
▸ We cannot cover all cases.
UNIT TEST EXAMPLE: SOLUTION
type Thing struct{}
type DataAccessLayer interface {
Insert(collectionName string, docs interface{}) error
}
func InsertThing(dal DataAccessLayer, doc *Thing) error {
if err := dal.Insert("things", doc); err != nil {
log.Println(err)
return err
}
return nil
}
▸ We don' t need a real DB Connection.
▸ We can cover all cases now.
So far, at Sendo, we've had a very big source base.
How to apply delegation ?
Refactor it. Use Clean Architecture
CLEAN ARCHITECTURE
CLEAN ARCHITECTURE: SCALE TO FIT SENDO
USE CASE REPOSITORY MODEL
Implement all RPC methods
Business logic for each method
Implement data accessing
Computing/Processing data
Business model
Implement some validations
Independent flow: Interfaces
CLEAN ARCHITECTURE: SCALE TO FIT SENDO (EXAMPLE)
USE CASE REPOSITORY MODEL
UpdateProduct(product) Product
FindProductById(id)
UpdateProduct(product)
MONGO
FindProductById(id)
UpdateProduct(product)
REDIS
Very simple for micro services
That means it's very easy to test
Unit Test, the right way with TDD
Test Driven Development
TEST DRIVEN DEVELOPMENT FLOW
Write failing test
Run and fail test
Write code to pass
Run and pass test
Refactor
Well, we write Unit Test without
implementing main business logic
It's crazy !!!
That's the way Unit Test is tested.
We never do Unit Test for Unit Test !
Unit Test with CI (Gitlab)
Demo TDD by Coding
Quiz
Thank you

More Related Content

What's hot

Networking in Java with NIO and Netty
Networking in Java with NIO and NettyNetworking in Java with NIO and Netty
Networking in Java with NIO and NettyConstantine Slisenka
 
Load Testing - How to Stress Your Odoo with Locust
Load Testing - How to Stress Your Odoo with LocustLoad Testing - How to Stress Your Odoo with Locust
Load Testing - How to Stress Your Odoo with LocustOdoo
 
Menu bars and menus
Menu bars and menusMenu bars and menus
Menu bars and menusmyrajendra
 
Capabilities for Resources and Effects
Capabilities for Resources and EffectsCapabilities for Resources and Effects
Capabilities for Resources and EffectsMartin Odersky
 
Reactive Web 101: WebFlux, WebClient, and Reactor Netty
Reactive Web 101: WebFlux, WebClient, and Reactor NettyReactive Web 101: WebFlux, WebClient, and Reactor Netty
Reactive Web 101: WebFlux, WebClient, and Reactor NettyVMware Tanzu
 
Node.js File system & Streams
Node.js File system & StreamsNode.js File system & Streams
Node.js File system & StreamsEyal Vardi
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...Claudio Capobianco
 
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023Steve Pember
 
Py.test
Py.testPy.test
Py.testsoasme
 
An Introduction of Node Package Manager (NPM)
An Introduction of Node Package Manager (NPM)An Introduction of Node Package Manager (NPM)
An Introduction of Node Package Manager (NPM)iFour Technolab Pvt. Ltd.
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first stepsRenato Primavera
 

What's hot (20)

Networking in Java with NIO and Netty
Networking in Java with NIO and NettyNetworking in Java with NIO and Netty
Networking in Java with NIO and Netty
 
Load Testing - How to Stress Your Odoo with Locust
Load Testing - How to Stress Your Odoo with LocustLoad Testing - How to Stress Your Odoo with Locust
Load Testing - How to Stress Your Odoo with Locust
 
Js scope
Js scopeJs scope
Js scope
 
Menu bars and menus
Menu bars and menusMenu bars and menus
Menu bars and menus
 
Capabilities for Resources and Effects
Capabilities for Resources and EffectsCapabilities for Resources and Effects
Capabilities for Resources and Effects
 
Reactive Web 101: WebFlux, WebClient, and Reactor Netty
Reactive Web 101: WebFlux, WebClient, and Reactor NettyReactive Web 101: WebFlux, WebClient, and Reactor Netty
Reactive Web 101: WebFlux, WebClient, and Reactor Netty
 
Node.js File system & Streams
Node.js File system & StreamsNode.js File system & Streams
Node.js File system & Streams
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...
 
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
Py.test
Py.testPy.test
Py.test
 
Unit Test
Unit TestUnit Test
Unit Test
 
XPath Injection
XPath InjectionXPath Injection
XPath Injection
 
Oop in kotlin
Oop in kotlinOop in kotlin
Oop in kotlin
 
Clean code
Clean codeClean code
Clean code
 
An Introduction of Node Package Manager (NPM)
An Introduction of Node Package Manager (NPM)An Introduction of Node Package Manager (NPM)
An Introduction of Node Package Manager (NPM)
 
Python my sql database connection
Python my sql   database connectionPython my sql   database connection
Python my sql database connection
 
Rest api with node js and express
Rest api with node js and expressRest api with node js and express
Rest api with node js and express
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 

Similar to Unit Test & TDD Workshop: Write Tests First

Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Developmentguestc8093a6
 
TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012Pietro Di Bello
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Gianluca Padovani
 
In search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testingIn search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testingAnna Khabibullina
 
Implicit classes - share the knowledge
Implicit classes  - share the knowledgeImplicit classes  - share the knowledge
Implicit classes - share the knowledgeJoão Caxaria
 
1 aleksandr gritsevski - attd example using
1   aleksandr gritsevski - attd example using1   aleksandr gritsevski - attd example using
1 aleksandr gritsevski - attd example usingIevgenii Katsan
 
Testing Django Applications
Testing Django ApplicationsTesting Django Applications
Testing Django ApplicationsHonza Král
 
RSpec: What, How and Why
RSpec: What, How and WhyRSpec: What, How and Why
RSpec: What, How and WhyRatan Sebastian
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testingpleeps
 
Test-Driven Development Introduction
Test-Driven Development IntroductionTest-Driven Development Introduction
Test-Driven Development IntroductionSamsung Electronics
 
TDD Flow: The Mantra in Action
TDD Flow: The Mantra in ActionTDD Flow: The Mantra in Action
TDD Flow: The Mantra in ActionDionatan default
 
TDD - survival guide
TDD - survival guide TDD - survival guide
TDD - survival guide vitalipe
 
Acceptance Testing With Selenium
Acceptance Testing With SeleniumAcceptance Testing With Selenium
Acceptance Testing With Seleniumelliando dias
 
Unit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and HowsUnit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and Howsatesgoral
 
Test Driven Development: Why I hate it; but secretly love it.
Test Driven Development: Why I hate it; but secretly love it. Test Driven Development: Why I hate it; but secretly love it.
Test Driven Development: Why I hate it; but secretly love it. Tom Crinson
 

Similar to Unit Test & TDD Workshop: Write Tests First (20)

Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012
 
Best practices unit testing
Best practices unit testing Best practices unit testing
Best practices unit testing
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)
 
In search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testingIn search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testing
 
Getting Started With Testing
Getting Started With TestingGetting Started With Testing
Getting Started With Testing
 
Implicit classes - share the knowledge
Implicit classes  - share the knowledgeImplicit classes  - share the knowledge
Implicit classes - share the knowledge
 
1 aleksandr gritsevski - attd example using
1   aleksandr gritsevski - attd example using1   aleksandr gritsevski - attd example using
1 aleksandr gritsevski - attd example using
 
Agile Android
Agile AndroidAgile Android
Agile Android
 
Testing Django Applications
Testing Django ApplicationsTesting Django Applications
Testing Django Applications
 
RSpec: What, How and Why
RSpec: What, How and WhyRSpec: What, How and Why
RSpec: What, How and Why
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Test-Driven Development Introduction
Test-Driven Development IntroductionTest-Driven Development Introduction
Test-Driven Development Introduction
 
Refactoring
RefactoringRefactoring
Refactoring
 
TDD Flow: The Mantra in Action
TDD Flow: The Mantra in ActionTDD Flow: The Mantra in Action
TDD Flow: The Mantra in Action
 
TDD - survival guide
TDD - survival guide TDD - survival guide
TDD - survival guide
 
Agile mobile
Agile mobileAgile mobile
Agile mobile
 
Acceptance Testing With Selenium
Acceptance Testing With SeleniumAcceptance Testing With Selenium
Acceptance Testing With Selenium
 
Unit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and HowsUnit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and Hows
 
Test Driven Development: Why I hate it; but secretly love it.
Test Driven Development: Why I hate it; but secretly love it. Test Driven Development: Why I hate it; but secretly love it.
Test Driven Development: Why I hate it; but secretly love it.
 

Recently uploaded

Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 

Recently uploaded (20)

Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
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...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 

Unit Test & TDD Workshop: Write Tests First

  • 1. Unit Test & TDD Sendo Workshop Viet Tran - Sendo Software Architect viettranx@gmail.com
  • 2. AGENDA ▸ Unit Test: What & Why ▸ Current problems at Sendo and solution ▸ Clean Architecture ▸ TDD - Test Development Driven ▸ Demo: Write Unit Test, the right way
  • 3. WHAT IS UNIT TEST ? Unit testing is a software development process in which the smallest testable parts of an application, called units, are individually and independently scrutinized for proper operation.
  • 4. WHY UNIT TEST ? ▸ Unit tests detect changes that may break a design contract ▸ Standardize: Unit testing improves the quality of code ▸ Unit testing helps reduce the cost of bug fixes ▸ It's fun
  • 5. EXAMPLE FOR UNIT TEST func Sum(x int, y int) int { return x + y } func TestSum(t *testing.T) { total := Sum(5, 5) expect := 10 assert.Equal(t, 10, total, "should be qual") }
  • 6. EXAMPLE FOR UNIT TEST func Sum(x int, y int) int { return x + y } func TestSum(t *testing.T) { tables := []struct { args []int expect int }{ {[]int{5,5}, 10}, {[]int{8,9}, 17}, {[]int{1,0}, 1}, } for _, c := tables { actual := Sum(c.args[0], c.args[1]) assert.Equal(t, actual, c.expect, "should be qual") } }
  • 7. LAUNCHING TESTS $ go test -v This picks up any files matching packagename_test.go $ go test -cover PASS coverage: 66.67% of statements
  • 8. CURRENT PROBLEMS AT SENDO ▸ Have no Unit Test, QC have to test manually and full flow. ▸ High tightly coding, every change might break the others. ▸ Huge function body, very hard to maintain. ▸ CI/CD does not support Unit Test checking.
  • 9. CURRENT PROBLEMS AT SENDO (CONTINUE) LOGIC 1 LOGIC 2 LOGIC 3 LOGIC ...Huge Function DBConcrete Objects REST CALL SERVICE CALL It's very hard to maintain these stuff
  • 10. Most of problems in software development can be solved by delegation
  • 11. HOW DOES DELEGATION WORKS ? LOGIN CONCRETE LOGIN DB I know who you are and what exactly you can do I need to login Just wait until I finish my job
  • 12. HOW DOES DELEGATION WORKS ? (CONTINUE) LOGIN CONCRETE LOGIN DB I don't know who you are but what exactly you can do I need to login Just call and I will implement it. DELEGATION / ABSTRACTION
  • 13. HOW DOES DELEGATION WORKS ? COME TO TESTING LOGIN TEST MOCK LOGIN DB Independently testing: Testing without real DB connection I need to run testing Simulate all cases of login function DELEGATION / ABSTRACTION
  • 14. Instead of direct calling, we use delegation
  • 15. UNIT TEST EXAMPLE: IS IT A GOOD PRACTICE ? type Thing struct{} func InsertThing(doc *Thing) error { session, err := mgo.Dial("localhost") if err != nil { return errors.New("Can not connect to db") } defer session.Close() db := session.DB("test") db.Collection("things").Insert(doc); err != nil { return errors.New("Can not insert thing") } return nil }
  • 16. UNIT TEST EXAMPLE: IS IT A GOOD PRACTICE ? (CONT.) It's bad practice. WHY ? type Thing struct{} func InsertThing(doc *Thing) error { session, err := mgo.Dial("localhost") if err != nil { return errors.New("Can not connect to db") } defer session.Close() db := session.DB("test") db.Collection("things").Insert(doc); err != nil { return errors.New("Can not insert thing") } return nil }
  • 17. UNIT TEST EXAMPLE (CONTINUE) type Thing struct{} func InsertThing(doc *Thing) error { session, err := mgo.Dial("localhost") if err != nil { return errors.New("Can not connect to db") } defer session.Close() db := session.DB("test") db.Collection("things").Insert(doc); err != nil { return errors.New("Can not insert thing") } return nil } CONNECT DB INSERT THING
  • 18. UNIT TEST EXAMPLE (CONTINUE) func TestInsertThing(t *testing.T) { doc := Thing{} err := InsertThing(&doc) assert.NotNil(t, err, "should be not nil") } A basic Unit Test for InsertThing
  • 19. UNIT TEST EXAMPLE (COVERAGE) type Thing struct{} func InsertThing(doc *Thing) error { session, err := mgo.Dial("localhost") if err != nil { return errors.New("Can not connect to db") } defer session.Close() db := session.DB("test") db.Collection("things").Insert(doc); err != nil { return errors.New("Can not insert thing") } return nil } func TestInsertThing(t *testing.T) { doc := Thing{} err := InsertThing(&doc) assert.NotNil(t, err, "should be not nil") } ▸ We need a real DB Connection. ▸ We cannot cover all cases.
  • 20. UNIT TEST EXAMPLE: SOLUTION type Thing struct{} type DataAccessLayer interface { Insert(collectionName string, docs interface{}) error } func InsertThing(dal DataAccessLayer, doc *Thing) error { if err := dal.Insert("things", doc); err != nil { log.Println(err) return err } return nil } ▸ We don' t need a real DB Connection. ▸ We can cover all cases now.
  • 21. So far, at Sendo, we've had a very big source base. How to apply delegation ?
  • 22. Refactor it. Use Clean Architecture
  • 24. CLEAN ARCHITECTURE: SCALE TO FIT SENDO USE CASE REPOSITORY MODEL Implement all RPC methods Business logic for each method Implement data accessing Computing/Processing data Business model Implement some validations Independent flow: Interfaces
  • 25. CLEAN ARCHITECTURE: SCALE TO FIT SENDO (EXAMPLE) USE CASE REPOSITORY MODEL UpdateProduct(product) Product FindProductById(id) UpdateProduct(product) MONGO FindProductById(id) UpdateProduct(product) REDIS Very simple for micro services
  • 26. That means it's very easy to test
  • 27. Unit Test, the right way with TDD Test Driven Development
  • 28. TEST DRIVEN DEVELOPMENT FLOW Write failing test Run and fail test Write code to pass Run and pass test Refactor
  • 29. Well, we write Unit Test without implementing main business logic It's crazy !!!
  • 30. That's the way Unit Test is tested. We never do Unit Test for Unit Test !
  • 31. Unit Test with CI (Gitlab)
  • 32. Demo TDD by Coding
  • 33. Quiz