SlideShare a Scribd company logo
1 of 24
Pegomock
A mocking framework for Go
2018
Peter Goetz
1
peter.gtz@gmail.com
github.com/petergtz
twitter.com/petergtz
medium.com/@peter.gtz
Unit Tests
2
func sortInts(a []int) { /* ... */ }
ints := []int{8, 3, 6, 2, 7}
sortInts(ints)
Expect(ints).To(Equal([]int{2, 3, 6, 7, 8}))
DEPENDENCY INJECTION
3
Example: CheckoutService
4
Checkout-
Service
Shipping
-Service
CreditCard-
Service
Order-
Service
Example: CheckoutService
5
func (cs *CheckoutService) CheckOut(shoppingCart ShoppingCart) error {
sum := sumItemPricesIn(shoppingCart)
sum += cs.shippingService.GetShippingCosts()
err := cs.creditCardService.Charge(sum)
if err != nil {
return wrapped(err)
}
err = cs.orderService.Submit(shoppingCart)
if err != nil {
return wrapped(err)
}
return nil
}
How to test this method?
Example: CheckoutService
6
type CheckoutService struct {
shippingService *ShippingService
creditCardService *CreditCardService
orderService *OrderService
}
func NewCheckoutService() *CheckoutService {
return &CheckoutService{
NewShippingService(...),
NewCreditCardService(...),
NewOrderService(...),
}
}
Example: CheckoutService
7
Checkout-
Service
Http-
Shipping
-Service
gRPC-
CreditCard-
Service
Http-
Order-
Service
Imple-
mentation
Interface
Dependency
Legend:
Shipping-
Service
Order-
Service
CreditCard-
Service
Dependency Injection
8
type ShippingService interface {
GetShippingCosts() (costs Currency)
}
type CreditCardService interface {
Charge(amount Currency) error
}
type OrderService interface {
Submit(ShoppingCart) error
}
type CheckoutService struct {
shippingService ShippingService
creditCardService CreditCardService
orderService OrderService
}
func NewCheckoutService(
shippingService ShippingService,
creditCardService CreditCardService,
orderService OrderService) *CheckoutService {
return &CheckoutService{
shippingService,
creditCardService,
orderService,
}
}
Unit Testing the CheckoutService
9
fakeShippingService := ...
fakeCreditCardService := ...
fakeOrderService := ...
checkoutService := NewCheckoutService(
fakeShippingService,
fakeCreditCardService,
fakeOrderService)
When(fakeShippingService.GetShippingCost()).ThenReturn(5.90)
shoppingCart := ShoppingCart{[]Items{
Item{
Name: "Creation: Life and How to Make it - Steve Grand",
Price: 23.49,
},
}}
checkoutService.CheckOut(shoppingCart)
fakeCreditCardService.VerifyWasCalledOnce().Charge(15.90)
fakeOrderService.VerifyWasCalledOnce().Submit(shoppingCart)
Unit Testing the CheckoutService
10
fakeShippingService := NewMockShippingService()
fakeCreditCardService := NewMockCreditCardService()
fakeOrderService := NewMockOrderService()
checkoutService := NewCheckoutService(
fakeShippingService,
fakeCreditCardService,
fakeOrderService)
When(fakeShippingService.GetShippingCost()).ThenReturn(5.90)
shoppingCart := ShoppingCart{[]Items{
Item{
Name: "Creation: Life and How to Make it - Steve Grand",
Price: 23.49,
},
}}
checkoutService.CheckOut(shoppingCart)
fakeCreditCardService.VerifyWasCalledOnce().Charge(15.90)
fakeOrderService.VerifyWasCalledOnce().Submit(shoppingCart)
Generated by Pegomock
Pegomock CLI
11
# Install it:
go get github.com/petergtz/pegomock
go get github.com/petergtz/pegomock/pegomock
# Generate mocks:
pegomock generate ShippingService
pegomock generate CreditCardService
pegomock generate OrderService
PEGOMOCK DSL
12
Argument Matchers
Verification:
13
display := NewMockDisplay()
// Calling mock
display.Show("Hello again!")
// Verification:
display.VerifyWasCalledOnce().Show(AnyString())
Argument Matchers
Stubbing:
14
phoneBook := NewMockPhoneBook()
// Stubbing:
phoneBook.GetPhoneNumber(AnyString()).ThenReturn("123-456-789")
// Prints "123-456-789":
fmt.Println(phoneBook.GetPhoneNumber("Dan"))
// Also prints "123-456-789":
fmt.Println(phoneBook.GetPhoneNumber("Tom"))
Verifying Number of Invocations
15
display := NewMockDisplay()
// Calling mock
display.Show("Hello")
display.Show("Hello, again")
display.Show("And again")
// Verification:
display.VerifyWasCalled(Times(3)).Show(AnyString())
// or:
display.VerifyWasCalled(AtLeast(3)).Show(AnyString())
// or:
display.VerifyWasCalled(Never()).Show("This one was never called")
Verifying in Order
16
display1 := NewMockDisplay()
display2 := NewMockDisplay()
// Calling mocks
display1.Show("One")
display1.Show("Two")
display2.Show("Another two")
display1.Show("Three")
// Verification:
inOrderContext := new(InOrderContext)
display1.VerifyWasCalledInOrder(Once(), inOrderContext).Show("One")
display2.VerifyWasCalledInOrder(Once(), inOrderContext).Show("Another two")
display1.VerifyWasCalledInOrder(Once(), inOrderContext).Show("Three")
Stubbing with Callbacks
17
phoneBook := NewMockPhoneBook()
// Stubbing:
When(phoneBook.GetPhoneNumber(AnyString())).Then(func(params []Param) ReturnValues {
return []ReturnValue{fmt.Sprintf("1-800-CALL-%v", strings.ToUpper(params[0]))}
}
// Prints "1-800-CALL-DAN":
fmt.Println(phoneBook.GetPhoneNumber("Dan"))
// Prints "1-800-CALL-TOM”:
fmt.Println(phoneBook.GetPhoneNumber("Tom"))
Verifying with Argument Capture
18
display := NewMockDisplay()
// Calling mock
display.Show("Hello")
display.Show("Hello, again")
display.Show("And again")
// Verification and getting captured arguments
text := display.VerifyWasCalled(AtLeast(1)).Show(AnyString()).getCapturedArguments()
// Captured arguments are from last invocation
Expect(text).To(Equal("And again"))
Verifying with Argument Capture
19
display := NewMockDisplay()
// Calling mock
display.Show("Hello")
display.Show("Hello, again")
display.Show("And again")
// Verification and getting all captured arguments
texts := display.VerifyWasCalled(AtLeast(1)).Show(AnyString()).getAllCapturedArguments()
// Captured arguments are a slice
Expect(texts).To(ConsistOf("Hello", "Hello, again", "And again"))
Why Pegomock, why not X?
• https://github.com/golang/mock
• https://github.com/maxbrunsfeld/counterfeiter
• Any others
20
Where X is:
GoMock
21
GoMock:
Use the mock in a test:
func TestMyThing(t *testing.T) {
mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
mockObj := something.NewMockMyInterface(mockCtrl)
mockObj.EXPECT().SomeMethod(4, "blah")
// pass mockObj to a real object and play with it.
}
Pegomock:
func TestUsingMocks(t *testing.T) {
pegomock.RegisterMockTestingT(t)
mockObj := NewMyInterfaceMock()
// pass mockObj to a real object and play with it.
}
Counterfeiter
22
Counterfeiter:
fake.DoThings("stuff", 5)
Expect(fake.DoThingsCallCount()).To(Equal(1))
str, num := fake.DoThingsArgsForCall(0)
Expect(str).To(Equal("stuff"))
Expect(num).To(Equal(uint64(5)))
Pegomock:
fake.DoThings("stuff", 5)
fake.VerifyWasCalledOnce().DoThings("stuff", 5)
PEGOMOCK DEMO
23
Q & A
24
https://github.com/petergtz/pegomock
peter.gtz@gmail.com
github.com/petergtz
twitter.com/petergtz
medium.com/@peter.gtz

More Related Content

What's hot

Diseño de software en arquitectura cliente servidor
Diseño de software en arquitectura cliente   servidorDiseño de software en arquitectura cliente   servidor
Diseño de software en arquitectura cliente servidorCintia Cadena
 
Course 101: Lecture 5: Linux & GNU
Course 101: Lecture 5: Linux & GNU Course 101: Lecture 5: Linux & GNU
Course 101: Lecture 5: Linux & GNU Ahmed El-Arabawy
 
초보자를 위한 Git & GitHub
초보자를 위한 Git & GitHub초보자를 위한 Git & GitHub
초보자를 위한 Git & GitHubYurim Jin
 
proyecto conexion netbeans con Mysql
proyecto conexion netbeans con Mysqlproyecto conexion netbeans con Mysql
proyecto conexion netbeans con MysqlBrenditaLr
 
Operating Systems 1 (1/12) - History
Operating Systems 1 (1/12) - HistoryOperating Systems 1 (1/12) - History
Operating Systems 1 (1/12) - HistoryPeter Tröger
 
Linux basic commands with examples
Linux basic commands with examplesLinux basic commands with examples
Linux basic commands with examplesabclearnn
 
PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and SessionsNisa Soomro
 
Course 102: Lecture 11: Environment Variables
Course 102: Lecture 11: Environment VariablesCourse 102: Lecture 11: Environment Variables
Course 102: Lecture 11: Environment VariablesAhmed El-Arabawy
 
DevOps Fest 2020. Дмитрий Кудрявцев. Реализация GitOps на Kubernetes. ArgoCD
DevOps Fest 2020. Дмитрий Кудрявцев. Реализация GitOps на Kubernetes. ArgoCDDevOps Fest 2020. Дмитрий Кудрявцев. Реализация GitOps на Kubernetes. ArgoCD
DevOps Fest 2020. Дмитрий Кудрявцев. Реализация GitOps на Kubernetes. ArgoCDDevOps_Fest
 
Linux User Management
Linux User ManagementLinux User Management
Linux User ManagementGaurav Mishra
 
Everything You Need to Know About HCL Notes 14
Everything You Need to Know About HCL Notes 14Everything You Need to Know About HCL Notes 14
Everything You Need to Know About HCL Notes 14panagenda
 
Course 102: Lecture 14: Users and Permissions
Course 102: Lecture 14: Users and PermissionsCourse 102: Lecture 14: Users and Permissions
Course 102: Lecture 14: Users and PermissionsAhmed El-Arabawy
 
Redis, base de datos NoSQL clave-valor
Redis, base de datos NoSQL clave-valorRedis, base de datos NoSQL clave-valor
Redis, base de datos NoSQL clave-valorAlberto Gimeno
 

What's hot (20)

GIT In Detail
GIT In DetailGIT In Detail
GIT In Detail
 
Diseño de software en arquitectura cliente servidor
Diseño de software en arquitectura cliente   servidorDiseño de software en arquitectura cliente   servidor
Diseño de software en arquitectura cliente servidor
 
Network programming
Network programmingNetwork programming
Network programming
 
Course 101: Lecture 5: Linux & GNU
Course 101: Lecture 5: Linux & GNU Course 101: Lecture 5: Linux & GNU
Course 101: Lecture 5: Linux & GNU
 
초보자를 위한 Git & GitHub
초보자를 위한 Git & GitHub초보자를 위한 Git & GitHub
초보자를 위한 Git & GitHub
 
Sistemas Operativos Mono Proceso
Sistemas Operativos Mono ProcesoSistemas Operativos Mono Proceso
Sistemas Operativos Mono Proceso
 
Git real slides
Git real slidesGit real slides
Git real slides
 
proyecto conexion netbeans con Mysql
proyecto conexion netbeans con Mysqlproyecto conexion netbeans con Mysql
proyecto conexion netbeans con Mysql
 
Operating Systems 1 (1/12) - History
Operating Systems 1 (1/12) - HistoryOperating Systems 1 (1/12) - History
Operating Systems 1 (1/12) - History
 
Linux file system
Linux file systemLinux file system
Linux file system
 
Linux basic commands with examples
Linux basic commands with examplesLinux basic commands with examples
Linux basic commands with examples
 
PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and Sessions
 
Course 102: Lecture 11: Environment Variables
Course 102: Lecture 11: Environment VariablesCourse 102: Lecture 11: Environment Variables
Course 102: Lecture 11: Environment Variables
 
DevOps Fest 2020. Дмитрий Кудрявцев. Реализация GitOps на Kubernetes. ArgoCD
DevOps Fest 2020. Дмитрий Кудрявцев. Реализация GitOps на Kubernetes. ArgoCDDevOps Fest 2020. Дмитрий Кудрявцев. Реализация GitOps на Kubernetes. ArgoCD
DevOps Fest 2020. Дмитрий Кудрявцев. Реализация GitOps на Kubernetes. ArgoCD
 
Linux User Management
Linux User ManagementLinux User Management
Linux User Management
 
Git cheat sheet
Git cheat sheetGit cheat sheet
Git cheat sheet
 
Self Healing Capabilities of Domino 10
Self Healing Capabilities of Domino 10Self Healing Capabilities of Domino 10
Self Healing Capabilities of Domino 10
 
Everything You Need to Know About HCL Notes 14
Everything You Need to Know About HCL Notes 14Everything You Need to Know About HCL Notes 14
Everything You Need to Know About HCL Notes 14
 
Course 102: Lecture 14: Users and Permissions
Course 102: Lecture 14: Users and PermissionsCourse 102: Lecture 14: Users and Permissions
Course 102: Lecture 14: Users and Permissions
 
Redis, base de datos NoSQL clave-valor
Redis, base de datos NoSQL clave-valorRedis, base de datos NoSQL clave-valor
Redis, base de datos NoSQL clave-valor
 

Similar to Pegomock, a mocking framework for Go

Version1.0 StartHTML000000232 EndHTML000065057 StartFragment0000.docx
Version1.0 StartHTML000000232 EndHTML000065057 StartFragment0000.docxVersion1.0 StartHTML000000232 EndHTML000065057 StartFragment0000.docx
Version1.0 StartHTML000000232 EndHTML000065057 StartFragment0000.docxtienboileau
 
Imagine a world without mocks
Imagine a world without mocksImagine a world without mocks
Imagine a world without mockskenbot
 
How to not write a boring test in Golang
How to not write a boring test in GolangHow to not write a boring test in Golang
How to not write a boring test in GolangDan Tran
 
When RV Meets CEP (RV 2016 Tutorial)
When RV Meets CEP (RV 2016 Tutorial)When RV Meets CEP (RV 2016 Tutorial)
When RV Meets CEP (RV 2016 Tutorial)Sylvain Hallé
 
Symfony (Unit, Functional) Testing.
Symfony (Unit, Functional) Testing.Symfony (Unit, Functional) Testing.
Symfony (Unit, Functional) Testing.Basel Issmail
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4Abed Bukhari
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoThe Software House
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testingVisual Engineering
 
mobl: Een DSL voor mobiele applicatieontwikkeling
mobl: Een DSL voor mobiele applicatieontwikkelingmobl: Een DSL voor mobiele applicatieontwikkeling
mobl: Een DSL voor mobiele applicatieontwikkelingDevnology
 
help me Java projectI put problem and my own code in the linkmy .pdf
help me Java projectI put problem and my own code in the linkmy .pdfhelp me Java projectI put problem and my own code in the linkmy .pdf
help me Java projectI put problem and my own code in the linkmy .pdfarihantmum
 
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRaimonds Simanovskis
 
Analysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsAnalysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsPVS-Studio
 

Similar to Pegomock, a mocking framework for Go (20)

Version1.0 StartHTML000000232 EndHTML000065057 StartFragment0000.docx
Version1.0 StartHTML000000232 EndHTML000065057 StartFragment0000.docxVersion1.0 StartHTML000000232 EndHTML000065057 StartFragment0000.docx
Version1.0 StartHTML000000232 EndHTML000065057 StartFragment0000.docx
 
Imagine a world without mocks
Imagine a world without mocksImagine a world without mocks
Imagine a world without mocks
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
How to not write a boring test in Golang
How to not write a boring test in GolangHow to not write a boring test in Golang
How to not write a boring test in Golang
 
When RV Meets CEP (RV 2016 Tutorial)
When RV Meets CEP (RV 2016 Tutorial)When RV Meets CEP (RV 2016 Tutorial)
When RV Meets CEP (RV 2016 Tutorial)
 
Symfony (Unit, Functional) Testing.
Symfony (Unit, Functional) Testing.Symfony (Unit, Functional) Testing.
Symfony (Unit, Functional) Testing.
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
 
Writing Good Tests
Writing Good TestsWriting Good Tests
Writing Good Tests
 
Ss
SsSs
Ss
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duo
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testing
 
mobl: Een DSL voor mobiele applicatieontwikkeling
mobl: Een DSL voor mobiele applicatieontwikkelingmobl: Een DSL voor mobiele applicatieontwikkeling
mobl: Een DSL voor mobiele applicatieontwikkeling
 
A Test of Strength
A Test of StrengthA Test of Strength
A Test of Strength
 
Leveraging Symfony2 Forms
Leveraging Symfony2 FormsLeveraging Symfony2 Forms
Leveraging Symfony2 Forms
 
Func up your code
Func up your codeFunc up your code
Func up your code
 
help me Java projectI put problem and my own code in the linkmy .pdf
help me Java projectI put problem and my own code in the linkmy .pdfhelp me Java projectI put problem and my own code in the linkmy .pdf
help me Java projectI put problem and my own code in the linkmy .pdf
 
Java script
Java scriptJava script
Java script
 
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
 
Analysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsAnalysis of Microsoft Code Contracts
Analysis of Microsoft Code Contracts
 
ddd+scala
ddd+scaladdd+scala
ddd+scala
 

Recently uploaded

Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 

Recently uploaded (20)

Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 

Pegomock, a mocking framework for Go

  • 1. Pegomock A mocking framework for Go 2018 Peter Goetz 1 peter.gtz@gmail.com github.com/petergtz twitter.com/petergtz medium.com/@peter.gtz
  • 2. Unit Tests 2 func sortInts(a []int) { /* ... */ } ints := []int{8, 3, 6, 2, 7} sortInts(ints) Expect(ints).To(Equal([]int{2, 3, 6, 7, 8}))
  • 5. Example: CheckoutService 5 func (cs *CheckoutService) CheckOut(shoppingCart ShoppingCart) error { sum := sumItemPricesIn(shoppingCart) sum += cs.shippingService.GetShippingCosts() err := cs.creditCardService.Charge(sum) if err != nil { return wrapped(err) } err = cs.orderService.Submit(shoppingCart) if err != nil { return wrapped(err) } return nil } How to test this method?
  • 6. Example: CheckoutService 6 type CheckoutService struct { shippingService *ShippingService creditCardService *CreditCardService orderService *OrderService } func NewCheckoutService() *CheckoutService { return &CheckoutService{ NewShippingService(...), NewCreditCardService(...), NewOrderService(...), } }
  • 8. Dependency Injection 8 type ShippingService interface { GetShippingCosts() (costs Currency) } type CreditCardService interface { Charge(amount Currency) error } type OrderService interface { Submit(ShoppingCart) error } type CheckoutService struct { shippingService ShippingService creditCardService CreditCardService orderService OrderService } func NewCheckoutService( shippingService ShippingService, creditCardService CreditCardService, orderService OrderService) *CheckoutService { return &CheckoutService{ shippingService, creditCardService, orderService, } }
  • 9. Unit Testing the CheckoutService 9 fakeShippingService := ... fakeCreditCardService := ... fakeOrderService := ... checkoutService := NewCheckoutService( fakeShippingService, fakeCreditCardService, fakeOrderService) When(fakeShippingService.GetShippingCost()).ThenReturn(5.90) shoppingCart := ShoppingCart{[]Items{ Item{ Name: "Creation: Life and How to Make it - Steve Grand", Price: 23.49, }, }} checkoutService.CheckOut(shoppingCart) fakeCreditCardService.VerifyWasCalledOnce().Charge(15.90) fakeOrderService.VerifyWasCalledOnce().Submit(shoppingCart)
  • 10. Unit Testing the CheckoutService 10 fakeShippingService := NewMockShippingService() fakeCreditCardService := NewMockCreditCardService() fakeOrderService := NewMockOrderService() checkoutService := NewCheckoutService( fakeShippingService, fakeCreditCardService, fakeOrderService) When(fakeShippingService.GetShippingCost()).ThenReturn(5.90) shoppingCart := ShoppingCart{[]Items{ Item{ Name: "Creation: Life and How to Make it - Steve Grand", Price: 23.49, }, }} checkoutService.CheckOut(shoppingCart) fakeCreditCardService.VerifyWasCalledOnce().Charge(15.90) fakeOrderService.VerifyWasCalledOnce().Submit(shoppingCart) Generated by Pegomock
  • 11. Pegomock CLI 11 # Install it: go get github.com/petergtz/pegomock go get github.com/petergtz/pegomock/pegomock # Generate mocks: pegomock generate ShippingService pegomock generate CreditCardService pegomock generate OrderService
  • 13. Argument Matchers Verification: 13 display := NewMockDisplay() // Calling mock display.Show("Hello again!") // Verification: display.VerifyWasCalledOnce().Show(AnyString())
  • 14. Argument Matchers Stubbing: 14 phoneBook := NewMockPhoneBook() // Stubbing: phoneBook.GetPhoneNumber(AnyString()).ThenReturn("123-456-789") // Prints "123-456-789": fmt.Println(phoneBook.GetPhoneNumber("Dan")) // Also prints "123-456-789": fmt.Println(phoneBook.GetPhoneNumber("Tom"))
  • 15. Verifying Number of Invocations 15 display := NewMockDisplay() // Calling mock display.Show("Hello") display.Show("Hello, again") display.Show("And again") // Verification: display.VerifyWasCalled(Times(3)).Show(AnyString()) // or: display.VerifyWasCalled(AtLeast(3)).Show(AnyString()) // or: display.VerifyWasCalled(Never()).Show("This one was never called")
  • 16. Verifying in Order 16 display1 := NewMockDisplay() display2 := NewMockDisplay() // Calling mocks display1.Show("One") display1.Show("Two") display2.Show("Another two") display1.Show("Three") // Verification: inOrderContext := new(InOrderContext) display1.VerifyWasCalledInOrder(Once(), inOrderContext).Show("One") display2.VerifyWasCalledInOrder(Once(), inOrderContext).Show("Another two") display1.VerifyWasCalledInOrder(Once(), inOrderContext).Show("Three")
  • 17. Stubbing with Callbacks 17 phoneBook := NewMockPhoneBook() // Stubbing: When(phoneBook.GetPhoneNumber(AnyString())).Then(func(params []Param) ReturnValues { return []ReturnValue{fmt.Sprintf("1-800-CALL-%v", strings.ToUpper(params[0]))} } // Prints "1-800-CALL-DAN": fmt.Println(phoneBook.GetPhoneNumber("Dan")) // Prints "1-800-CALL-TOM”: fmt.Println(phoneBook.GetPhoneNumber("Tom"))
  • 18. Verifying with Argument Capture 18 display := NewMockDisplay() // Calling mock display.Show("Hello") display.Show("Hello, again") display.Show("And again") // Verification and getting captured arguments text := display.VerifyWasCalled(AtLeast(1)).Show(AnyString()).getCapturedArguments() // Captured arguments are from last invocation Expect(text).To(Equal("And again"))
  • 19. Verifying with Argument Capture 19 display := NewMockDisplay() // Calling mock display.Show("Hello") display.Show("Hello, again") display.Show("And again") // Verification and getting all captured arguments texts := display.VerifyWasCalled(AtLeast(1)).Show(AnyString()).getAllCapturedArguments() // Captured arguments are a slice Expect(texts).To(ConsistOf("Hello", "Hello, again", "And again"))
  • 20. Why Pegomock, why not X? • https://github.com/golang/mock • https://github.com/maxbrunsfeld/counterfeiter • Any others 20 Where X is:
  • 21. GoMock 21 GoMock: Use the mock in a test: func TestMyThing(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() mockObj := something.NewMockMyInterface(mockCtrl) mockObj.EXPECT().SomeMethod(4, "blah") // pass mockObj to a real object and play with it. } Pegomock: func TestUsingMocks(t *testing.T) { pegomock.RegisterMockTestingT(t) mockObj := NewMyInterfaceMock() // pass mockObj to a real object and play with it. }
  • 22. Counterfeiter 22 Counterfeiter: fake.DoThings("stuff", 5) Expect(fake.DoThingsCallCount()).To(Equal(1)) str, num := fake.DoThingsArgsForCall(0) Expect(str).To(Equal("stuff")) Expect(num).To(Equal(uint64(5))) Pegomock: fake.DoThings("stuff", 5) fake.VerifyWasCalledOnce().DoThings("stuff", 5)