SlideShare a Scribd company logo
1 of 43
GoogleMock for Dummies
Outline
• What is Mock?
• What Is Google C++ Mocking Framework?
• Getting Started
• A Case for Mock Turtles
• Writing the Mock Class
• Using Mocks in Tests
• Setting Expectations
• Appendix
• Reference
What is Mock?
• We creates a mock object to test the behavior
of some other object
• An object that we want to mock has the
following characteristics:
 Supplies non-deterministic results (e.g. the current time).
 Has states that are difficult to create or reproduce (e.g. a network error).
 Is slow (e.g. a complete database, which would have to be initialized before
the test).
 Does not yet exist or may change behavior.
 Would have to include information and methods exclusively for testing
purposes (and not for its actual task).
What is Mock?
• For example, crash test dummy is a mock
object used to simulate the dynamic behavior
of a human in vehicle impacts
What Is Google C++ Mocking
Framework?
• A mock object implements the same interface
as a real object (so it can be used as one), but
lets you specify at run time how it will be used
and what it should do
Which methods will be called?
In which order?
How many times?
With what arguments?
What will they return?
What Is Google C++ Mocking
Framework?
• A mock allows you to check the interaction
between itself and code that uses it
• Google C++ Mocking Framework is a library
for creating mock classes and using them
What Is Google C++ Mocking
Framework?
• Using Google Mock involves three basic steps:
1. Use some simple macros to describe the
interface you want to mock, and they will expand
to the implementation of your mock class
2. Create some mock objects and specify its
expectations and behavior using an intuitive
syntax
3. Exercise code that uses the mock objects. Google
Mock will catch any violation of the expectations
as soon as it arises
Getting Started
• #include <gtest/gtest.h>
• #include <gmock/gmock.h>
A Case for Mock Turtles
• Suppose you are developing a graphics program
that relies on a API (say, Turtle) for drawing
• Run your program and compare the screen with a
golden screen snapshot to see if it does the right
thing
• What if the API has been upgraded? Re-run your
program and compare the screen with a up-to-
date golden screen snapshot?
• Instead of having your application talk to the
drawing API directly, wrap the API in an interface
and code to that interface
A Case for Mock Turtles
void foo(int i, char c)
{
……
// bar object is not maintained by
// your team
bar.method(i);
……
}
void foo(int i, char c)
{
……
// we can see how our function
// interact with bar object
mock_bar.method(i);
……
}
Getting Started
• This is the API we want to mock
Writing the Mock Class
- How to Define It
• Here are the simple steps you need to follow:
1. Derive a class MockTurtle from Turtle.
2. Take a virtual function of Turtle. Count how many
arguments it has.
3. Inside the child class, write
MOCK_METHODn()/MOCK_CONST_METHODn();,
where n is the number of the arguments.
4. Cut-and-paste the function name as the first
argument to the macro, and leave what's left as the
second argument.
5. Repeat until all virtual functions you want to mock
are done.
How about non-virtual function then? Overload function? Class template?
See http://code.google.com/p/googlemock/wiki/CookBook
Writing the Mock Class
- How to Define It
• After the process, you should have something
like:
Writing the Mock Class
- How to Define It
Writing the Mock Class
- Where to Put It
• Put the mock’s definition in mock_xxx.h so
that anyone want to use the mock only need
to include mock_xxx.h
Using Mocks in Tests
• The typical work flow is:
1. Import the Google Mock names from the testing namespace such
that you can use them unqualified.
2. Create some mock objects.
3. Specify your expectations on them (How many times will a
method be called? With what arguments? What should it do?
etc.).
4. Exercise some code that uses the mocks; optionally, check the
result using Google Test assertions. If a mock method is called
more than expected or with wrong arguments, you'll get an error
immediately.
5. When a mock is destructed, Google Mock will automatically
check whether all expectations on it have been satisfied.
Using Mocks in Tests
We expect that PenDown() is called at least
once.
Our painter object
will use Turtle object
to do the drawing.
googletest
assertion
Setting Expectations
• The key to using a mock object successfully is
to set the right expectations on it
• Too strict or too loose expectation is not good
Setting Expectations
- General Syntax
• use the EXPECT_CALL() macro to set an
expectation on a mock method
• Two arguments: first the mock object, and
then the method and its arguments
• Note that the two are separated by a comma
It’s a comma
Optional clauses that provide more
information about the expectation.
Setting Expectations
- General Syntax
• The turtle object's GetX() method will be
called five times, it will return 100 the first
time, 150 the second time, and then 200
every time
Matchers
- What Arguments Do We Expect?
• When a mock function takes arguments, we
must specify what arguments we are
expecting
• Matchers are more flexible
• A matcher is like a predicate and can test
whether an argument is what we'd expect
Maybe too strict?
A list of built-in matchers can be found on
http://code.google.com/p/googlemock/wiki/CheatSheet
Cardinalities
- How Many Times Will It Be Called?
• Times() is a clause can be specified follows an
EXPECT_CALL()
• We call its argument a cardinality as it tells
how many times the call should occur
• Times(cardinality) can:
 Repeat an expectation many times.
 A cardinality can be "fuzzy", just like a matcher can be.
Cardinalities
- How Many Times Will It Be Called?
• Times(0)
 Google Mock will report a Google Test failure whenever the function is
(wrongfully) called
• AtLeast(n)
 An example of fuzzy cardinalities. The call is expected at least n times.
• If Times() ommitted, Google Mock will infer the
cardinality
 If neither WillOnce() nor WillRepeatedly() is in the EXPECT_CALL(), the
inferred cardinality is Times(1).
 If there are n WillOnce()'s but no WillRepeatedly(), where n >= 1, the
cardinality is Times(n).
 If there are n WillOnce()'s and one WillRepeatedly(), where n >= 0, the
cardinality is Times(AtLeast(n)).
Cardinalities
- How Many Times Will It Be Called?
• How do Google Mock infer the cardinality?
WillRepeatedly()
WillOnce()
None one
None Times(1)
n ≥ 1 Times(n)
n ≥ 0 Times(AtLeast(n))
Actions
- What Should It Do?
• If the return type of a mock function is a built-
in type or a pointer, the function has a default
action. If you don't say anything, this behavior
will be used
 void function will just return.
 bool function will return false.
 Other functions will return 0.
Say something
Actions
- What Should It Do?
• If a mock function doesn't have a default
action, or the default action doesn't suit you,
you can specify the action to be taken each
time the expectation matches using a series of
WillOnce() clauses followed by an optional
WillRepeatedly()
Actions
- What Should It Do?
Actions
- What Should It Do?
Actions
- What Should It Do?
• What can we do inside WillOnce() besides
Return()? You can return a reference using
ReturnRef(variable), or invoke a pre-defined
function
See http://code.google.com/p/googlemock/wiki/CheatSheet#Actions
Invoke pre-defined function
Actions
- What Should It Do?
• EXPECT_CALL() statement evaluates the action
clause only once, even though the action may
be performed many times
Actions
- What Should It Do?
• Instead of returning 100, 101, 102, ..., consecutively,
this mock function will always return 100 as n++ is only
evaluated once, which means it will return 100, 0, 0, 0
• turtle.GetY() will return 100 the first time, but return 0
from the second time on, as returning 0 is the default
action for int functions
Postfix increment
Using Multiple Expectations
• Specify expectations on multiple mock
methods, which may be from multiple mock
objects
• Google Mock will search the expectations in
the reverse order they are defined, and stop
when an active expectation that matches the
arguments is found
• Newer rules override older ones!
Using Multiple Expectations
• If the matching expectation cannot take any
more calls, you will get an upper-bound-
violated failure
• If Forward(10) is called three times in a row,
the third time it will be an error, as the last
matching expectation (#2) has been saturated
Using Multiple Expectations
• Match in the reverse order?
• This allows a user to set up the default
expectations in a mock object's constructor or
the test fixture's set-up phase and then
customize the mock by writing more specific
expectations in the test body
• Put the one with more specific matchers after
the other
Ordered vs Unordered Calls
• The calls don't have to occur in the order the
expectations are specified
• Want all the expected calls to occur in a strict
order?
• Creating an object of type InSequence
Want to specify partial order?
See http://code.google.com/p/googlemock/wiki/CookBook
All Expectations Are Sticky
• Test that the turtle is asked to go to the origin
exactly twice. What if GOTO(0, 0) called 3
times?
• Expectations in Google Mock are "sticky" by
default, in the sense that they remain active
even after we have reached their invocation
upper bounds
All Expectations Are Sticky
• turtle.GetX() will be called n times and will
return 10, 20, 30, ..., consecutively?
• The second time turtle.GetX() is called, the
last (latest) EXPECT_CALL() statement will
match. It’s a "upper bound exceeded" error!
All Expectations Are Sticky
• How to make expectation not sticky?
• Use RetiresOnSaturation()
• turtle.GetX() will return 10, 20, 30, ...
It should retire as soon as it is
saturated.
All Expectations Are Sticky
• The other situation where an expectation may
not be sticky is when it's in a sequence
• As soon as another expectation that comes
after it in the sequence has been used, it
automatically retires
Uninteresting Calls
• In Google Mock, if you are not interested in a
method, just don't say anything about it
• If a call to this method occurs, you'll see a
warning in the test output, but it won't be a
failure
Appendix
- Mocks and fakes
• Fakes implement the same interface as the
object that they represent and returning pre-
arranged responses
• Mocks do a little more. They will examine the
context of each call
 Checking the order in which its methods are called.
 Performing tests on the data passed into the method calls as arguments.
Appendix
- Mocks and fakes
• Fake objects have working implementations,
but usually take some shortcut (perhaps to
make the operations less expensive), which
makes them not suitable for production. An
in-memory file system would be an example
of a fake.
• Mocks are objects pre-programmed with
expectations, which form a specification of the
calls they are expected to receive
Reference
• http://code.google.com/p/googlemock/wiki/ForDummies
• http://en.wikipedia.org/wiki/Mock_object

More Related Content

What's hot

Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkArulalan T
 
How to test models using php unit testing framework?
How to test models using php unit testing framework?How to test models using php unit testing framework?
How to test models using php unit testing framework?satejsahu
 
Why Your Test Suite Sucks - PHPCon PL 2015
Why Your Test Suite Sucks - PHPCon PL 2015Why Your Test Suite Sucks - PHPCon PL 2015
Why Your Test Suite Sucks - PHPCon PL 2015CiaranMcNulty
 
Describe's Full of It's
Describe's Full of It'sDescribe's Full of It's
Describe's Full of It'sJim Lynch
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everythingnoelrap
 
Angular Unit Testing NDC Minn 2018
Angular Unit Testing NDC Minn 2018Angular Unit Testing NDC Minn 2018
Angular Unit Testing NDC Minn 2018Justin James
 
Angular Unit Testing from the Trenches
Angular Unit Testing from the TrenchesAngular Unit Testing from the Trenches
Angular Unit Testing from the TrenchesJustin James
 
Prefix casting versus as-casting in c#
Prefix casting versus as-casting in c#Prefix casting versus as-casting in c#
Prefix casting versus as-casting in c#Paul Houle
 
iOS Unit Testing
iOS Unit TestingiOS Unit Testing
iOS Unit Testingsgleadow
 
Hotfixing iOS apps with Javascript
Hotfixing iOS apps with JavascriptHotfixing iOS apps with Javascript
Hotfixing iOS apps with JavascriptSergio Padrino Recio
 
Testing the Untestable
Testing the UntestableTesting the Untestable
Testing the UntestableMark Baker
 

What's hot (16)

Mockito
MockitoMockito
Mockito
 
Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-framework
 
How to test models using php unit testing framework?
How to test models using php unit testing framework?How to test models using php unit testing framework?
How to test models using php unit testing framework?
 
Why Your Test Suite Sucks - PHPCon PL 2015
Why Your Test Suite Sucks - PHPCon PL 2015Why Your Test Suite Sucks - PHPCon PL 2015
Why Your Test Suite Sucks - PHPCon PL 2015
 
Describe's Full of It's
Describe's Full of It'sDescribe's Full of It's
Describe's Full of It's
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everything
 
Angular Unit Testing NDC Minn 2018
Angular Unit Testing NDC Minn 2018Angular Unit Testing NDC Minn 2018
Angular Unit Testing NDC Minn 2018
 
Angular Unit Testing from the Trenches
Angular Unit Testing from the TrenchesAngular Unit Testing from the Trenches
Angular Unit Testing from the Trenches
 
Mocking with Mockito
Mocking with MockitoMocking with Mockito
Mocking with Mockito
 
Prefix casting versus as-casting in c#
Prefix casting versus as-casting in c#Prefix casting versus as-casting in c#
Prefix casting versus as-casting in c#
 
iOS Unit Testing
iOS Unit TestingiOS Unit Testing
iOS Unit Testing
 
Hotfixing iOS apps with Javascript
Hotfixing iOS apps with JavascriptHotfixing iOS apps with Javascript
Hotfixing iOS apps with Javascript
 
L2624 labriola
L2624 labriolaL2624 labriola
L2624 labriola
 
Testing the Untestable
Testing the UntestableTesting the Untestable
Testing the Untestable
 
Automate Design Patterns
Automate Design PatternsAutomate Design Patterns
Automate Design Patterns
 
Using Mockito
Using MockitoUsing Mockito
Using Mockito
 

Viewers also liked

ITCamp 2012 - Paula Januszkiewicz - Stronghold to Strengthen
ITCamp 2012 - Paula Januszkiewicz - Stronghold to StrengthenITCamp 2012 - Paula Januszkiewicz - Stronghold to Strengthen
ITCamp 2012 - Paula Januszkiewicz - Stronghold to StrengthenITCamp
 
Secure development of code
Secure development of codeSecure development of code
Secure development of codeSalomeVictor
 
A New Tracer for Reverse Engineering - PacSec 2010
A New Tracer for Reverse Engineering - PacSec 2010A New Tracer for Reverse Engineering - PacSec 2010
A New Tracer for Reverse Engineering - PacSec 2010Tsukasa Oi
 
CiklumCPPSat24032012:ArtyomBondartsov-MicrosoftDetours&GoogleMockForC++InDeve...
CiklumCPPSat24032012:ArtyomBondartsov-MicrosoftDetours&GoogleMockForC++InDeve...CiklumCPPSat24032012:ArtyomBondartsov-MicrosoftDetours&GoogleMockForC++InDeve...
CiklumCPPSat24032012:ArtyomBondartsov-MicrosoftDetours&GoogleMockForC++InDeve...Ciklum Ukraine
 
I haz you and pwn your maal whitepaper
I haz you and pwn your maal whitepaperI haz you and pwn your maal whitepaper
I haz you and pwn your maal whitepaperHarsimran Walia
 
Sebastián Guerrero - Pimp your Android [RootedCON 2012]
Sebastián Guerrero - Pimp your Android [RootedCON 2012]Sebastián Guerrero - Pimp your Android [RootedCON 2012]
Sebastián Guerrero - Pimp your Android [RootedCON 2012]RootedCON
 

Viewers also liked (8)

ITCamp 2012 - Paula Januszkiewicz - Stronghold to Strengthen
ITCamp 2012 - Paula Januszkiewicz - Stronghold to StrengthenITCamp 2012 - Paula Januszkiewicz - Stronghold to Strengthen
ITCamp 2012 - Paula Januszkiewicz - Stronghold to Strengthen
 
Secure development of code
Secure development of codeSecure development of code
Secure development of code
 
A New Tracer for Reverse Engineering - PacSec 2010
A New Tracer for Reverse Engineering - PacSec 2010A New Tracer for Reverse Engineering - PacSec 2010
A New Tracer for Reverse Engineering - PacSec 2010
 
CiklumCPPSat24032012:ArtyomBondartsov-MicrosoftDetours&GoogleMockForC++InDeve...
CiklumCPPSat24032012:ArtyomBondartsov-MicrosoftDetours&GoogleMockForC++InDeve...CiklumCPPSat24032012:ArtyomBondartsov-MicrosoftDetours&GoogleMockForC++InDeve...
CiklumCPPSat24032012:ArtyomBondartsov-MicrosoftDetours&GoogleMockForC++InDeve...
 
Taller2
Taller2Taller2
Taller2
 
I haz you and pwn your maal whitepaper
I haz you and pwn your maal whitepaperI haz you and pwn your maal whitepaper
I haz you and pwn your maal whitepaper
 
Inside winnyp
Inside winnypInside winnyp
Inside winnyp
 
Sebastián Guerrero - Pimp your Android [RootedCON 2012]
Sebastián Guerrero - Pimp your Android [RootedCON 2012]Sebastián Guerrero - Pimp your Android [RootedCON 2012]
Sebastián Guerrero - Pimp your Android [RootedCON 2012]
 

Similar to Google mock for dummies

CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!Ortus Solutions, Corp
 
Just Mock It - Mocks and Stubs
Just Mock It - Mocks and StubsJust Mock It - Mocks and Stubs
Just Mock It - Mocks and StubsGavin Pickin
 
Python mocking intro
Python mocking introPython mocking intro
Python mocking introHans Jones
 
A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)Thierry Gayet
 
Devday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvuDevday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvuPhat VU
 
Unit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - KenyaUnit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - KenyaErick M'bwana
 
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...DevDay.org
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMockYing Zhang
 
Google mock training
Google mock trainingGoogle mock training
Google mock trainingThierry Gayet
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentAll Things Open
 
Building unit tests correctly
Building unit tests correctlyBuilding unit tests correctly
Building unit tests correctlyDror Helper
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock TutorialSbin m
 
谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testabilitydrewz lin
 
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in FlexassertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flexmichael.labriola
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock FrameworkEugene Dvorkin
 

Similar to Google mock for dummies (20)

CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!
 
Just Mock It - Mocks and Stubs
Just Mock It - Mocks and StubsJust Mock It - Mocks and Stubs
Just Mock It - Mocks and Stubs
 
Python mocking intro
Python mocking introPython mocking intro
Python mocking intro
 
A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)
 
Devday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvuDevday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvu
 
Unit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - KenyaUnit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - Kenya
 
EasyMock for Java
EasyMock for JavaEasyMock for Java
EasyMock for Java
 
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
 
Google mock training
Google mock trainingGoogle mock training
Google mock training
 
Grails Spock Testing
Grails Spock TestingGrails Spock Testing
Grails Spock Testing
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Easy mock
Easy mockEasy mock
Easy mock
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End Development
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
Building unit tests correctly
Building unit tests correctlyBuilding unit tests correctly
Building unit tests correctly
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock Tutorial
 
谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability
 
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in FlexassertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock Framework
 

More from Fraboni Ec

Hardware multithreading
Hardware multithreadingHardware multithreading
Hardware multithreadingFraboni Ec
 
What is simultaneous multithreading
What is simultaneous multithreadingWhat is simultaneous multithreading
What is simultaneous multithreadingFraboni Ec
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherenceFraboni Ec
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data miningFraboni Ec
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data miningFraboni Ec
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discoveryFraboni Ec
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching worksFraboni Ec
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cacheFraboni Ec
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsFraboni Ec
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and pythonFraboni Ec
 
Abstract data types
Abstract data typesAbstract data types
Abstract data typesFraboni Ec
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsFraboni Ec
 
Abstraction file
Abstraction fileAbstraction file
Abstraction fileFraboni Ec
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysisFraboni Ec
 
Abstract class
Abstract classAbstract class
Abstract classFraboni Ec
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaFraboni Ec
 

More from Fraboni Ec (20)

Hardware multithreading
Hardware multithreadingHardware multithreading
Hardware multithreading
 
Lisp
LispLisp
Lisp
 
What is simultaneous multithreading
What is simultaneous multithreadingWhat is simultaneous multithreading
What is simultaneous multithreading
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherence
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data mining
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data mining
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discovery
 
Cache recap
Cache recapCache recap
Cache recap
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching works
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cache
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and python
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessors
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
 
Object model
Object modelObject model
Object model
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysis
 
Abstract class
Abstract classAbstract class
Abstract class
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Inheritance
InheritanceInheritance
Inheritance
 

Recently uploaded

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
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
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
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
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
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
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
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
 
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
 

Recently uploaded (20)

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
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
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.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
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
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
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
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
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
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
 
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
 

Google mock for dummies

  • 2. Outline • What is Mock? • What Is Google C++ Mocking Framework? • Getting Started • A Case for Mock Turtles • Writing the Mock Class • Using Mocks in Tests • Setting Expectations • Appendix • Reference
  • 3. What is Mock? • We creates a mock object to test the behavior of some other object • An object that we want to mock has the following characteristics:  Supplies non-deterministic results (e.g. the current time).  Has states that are difficult to create or reproduce (e.g. a network error).  Is slow (e.g. a complete database, which would have to be initialized before the test).  Does not yet exist or may change behavior.  Would have to include information and methods exclusively for testing purposes (and not for its actual task).
  • 4. What is Mock? • For example, crash test dummy is a mock object used to simulate the dynamic behavior of a human in vehicle impacts
  • 5. What Is Google C++ Mocking Framework? • A mock object implements the same interface as a real object (so it can be used as one), but lets you specify at run time how it will be used and what it should do Which methods will be called? In which order? How many times? With what arguments? What will they return?
  • 6. What Is Google C++ Mocking Framework? • A mock allows you to check the interaction between itself and code that uses it • Google C++ Mocking Framework is a library for creating mock classes and using them
  • 7. What Is Google C++ Mocking Framework? • Using Google Mock involves three basic steps: 1. Use some simple macros to describe the interface you want to mock, and they will expand to the implementation of your mock class 2. Create some mock objects and specify its expectations and behavior using an intuitive syntax 3. Exercise code that uses the mock objects. Google Mock will catch any violation of the expectations as soon as it arises
  • 8. Getting Started • #include <gtest/gtest.h> • #include <gmock/gmock.h>
  • 9. A Case for Mock Turtles • Suppose you are developing a graphics program that relies on a API (say, Turtle) for drawing • Run your program and compare the screen with a golden screen snapshot to see if it does the right thing • What if the API has been upgraded? Re-run your program and compare the screen with a up-to- date golden screen snapshot? • Instead of having your application talk to the drawing API directly, wrap the API in an interface and code to that interface
  • 10. A Case for Mock Turtles void foo(int i, char c) { …… // bar object is not maintained by // your team bar.method(i); …… } void foo(int i, char c) { …… // we can see how our function // interact with bar object mock_bar.method(i); …… }
  • 11. Getting Started • This is the API we want to mock
  • 12. Writing the Mock Class - How to Define It • Here are the simple steps you need to follow: 1. Derive a class MockTurtle from Turtle. 2. Take a virtual function of Turtle. Count how many arguments it has. 3. Inside the child class, write MOCK_METHODn()/MOCK_CONST_METHODn();, where n is the number of the arguments. 4. Cut-and-paste the function name as the first argument to the macro, and leave what's left as the second argument. 5. Repeat until all virtual functions you want to mock are done. How about non-virtual function then? Overload function? Class template? See http://code.google.com/p/googlemock/wiki/CookBook
  • 13. Writing the Mock Class - How to Define It • After the process, you should have something like:
  • 14. Writing the Mock Class - How to Define It
  • 15. Writing the Mock Class - Where to Put It • Put the mock’s definition in mock_xxx.h so that anyone want to use the mock only need to include mock_xxx.h
  • 16. Using Mocks in Tests • The typical work flow is: 1. Import the Google Mock names from the testing namespace such that you can use them unqualified. 2. Create some mock objects. 3. Specify your expectations on them (How many times will a method be called? With what arguments? What should it do? etc.). 4. Exercise some code that uses the mocks; optionally, check the result using Google Test assertions. If a mock method is called more than expected or with wrong arguments, you'll get an error immediately. 5. When a mock is destructed, Google Mock will automatically check whether all expectations on it have been satisfied.
  • 17. Using Mocks in Tests We expect that PenDown() is called at least once. Our painter object will use Turtle object to do the drawing. googletest assertion
  • 18. Setting Expectations • The key to using a mock object successfully is to set the right expectations on it • Too strict or too loose expectation is not good
  • 19. Setting Expectations - General Syntax • use the EXPECT_CALL() macro to set an expectation on a mock method • Two arguments: first the mock object, and then the method and its arguments • Note that the two are separated by a comma It’s a comma Optional clauses that provide more information about the expectation.
  • 20. Setting Expectations - General Syntax • The turtle object's GetX() method will be called five times, it will return 100 the first time, 150 the second time, and then 200 every time
  • 21. Matchers - What Arguments Do We Expect? • When a mock function takes arguments, we must specify what arguments we are expecting • Matchers are more flexible • A matcher is like a predicate and can test whether an argument is what we'd expect Maybe too strict? A list of built-in matchers can be found on http://code.google.com/p/googlemock/wiki/CheatSheet
  • 22. Cardinalities - How Many Times Will It Be Called? • Times() is a clause can be specified follows an EXPECT_CALL() • We call its argument a cardinality as it tells how many times the call should occur • Times(cardinality) can:  Repeat an expectation many times.  A cardinality can be "fuzzy", just like a matcher can be.
  • 23. Cardinalities - How Many Times Will It Be Called? • Times(0)  Google Mock will report a Google Test failure whenever the function is (wrongfully) called • AtLeast(n)  An example of fuzzy cardinalities. The call is expected at least n times. • If Times() ommitted, Google Mock will infer the cardinality  If neither WillOnce() nor WillRepeatedly() is in the EXPECT_CALL(), the inferred cardinality is Times(1).  If there are n WillOnce()'s but no WillRepeatedly(), where n >= 1, the cardinality is Times(n).  If there are n WillOnce()'s and one WillRepeatedly(), where n >= 0, the cardinality is Times(AtLeast(n)).
  • 24. Cardinalities - How Many Times Will It Be Called? • How do Google Mock infer the cardinality? WillRepeatedly() WillOnce() None one None Times(1) n ≥ 1 Times(n) n ≥ 0 Times(AtLeast(n))
  • 25. Actions - What Should It Do? • If the return type of a mock function is a built- in type or a pointer, the function has a default action. If you don't say anything, this behavior will be used  void function will just return.  bool function will return false.  Other functions will return 0. Say something
  • 26. Actions - What Should It Do? • If a mock function doesn't have a default action, or the default action doesn't suit you, you can specify the action to be taken each time the expectation matches using a series of WillOnce() clauses followed by an optional WillRepeatedly()
  • 29. Actions - What Should It Do? • What can we do inside WillOnce() besides Return()? You can return a reference using ReturnRef(variable), or invoke a pre-defined function See http://code.google.com/p/googlemock/wiki/CheatSheet#Actions Invoke pre-defined function
  • 30. Actions - What Should It Do? • EXPECT_CALL() statement evaluates the action clause only once, even though the action may be performed many times
  • 31. Actions - What Should It Do? • Instead of returning 100, 101, 102, ..., consecutively, this mock function will always return 100 as n++ is only evaluated once, which means it will return 100, 0, 0, 0 • turtle.GetY() will return 100 the first time, but return 0 from the second time on, as returning 0 is the default action for int functions Postfix increment
  • 32. Using Multiple Expectations • Specify expectations on multiple mock methods, which may be from multiple mock objects • Google Mock will search the expectations in the reverse order they are defined, and stop when an active expectation that matches the arguments is found • Newer rules override older ones!
  • 33. Using Multiple Expectations • If the matching expectation cannot take any more calls, you will get an upper-bound- violated failure • If Forward(10) is called three times in a row, the third time it will be an error, as the last matching expectation (#2) has been saturated
  • 34. Using Multiple Expectations • Match in the reverse order? • This allows a user to set up the default expectations in a mock object's constructor or the test fixture's set-up phase and then customize the mock by writing more specific expectations in the test body • Put the one with more specific matchers after the other
  • 35. Ordered vs Unordered Calls • The calls don't have to occur in the order the expectations are specified • Want all the expected calls to occur in a strict order? • Creating an object of type InSequence Want to specify partial order? See http://code.google.com/p/googlemock/wiki/CookBook
  • 36. All Expectations Are Sticky • Test that the turtle is asked to go to the origin exactly twice. What if GOTO(0, 0) called 3 times? • Expectations in Google Mock are "sticky" by default, in the sense that they remain active even after we have reached their invocation upper bounds
  • 37. All Expectations Are Sticky • turtle.GetX() will be called n times and will return 10, 20, 30, ..., consecutively? • The second time turtle.GetX() is called, the last (latest) EXPECT_CALL() statement will match. It’s a "upper bound exceeded" error!
  • 38. All Expectations Are Sticky • How to make expectation not sticky? • Use RetiresOnSaturation() • turtle.GetX() will return 10, 20, 30, ... It should retire as soon as it is saturated.
  • 39. All Expectations Are Sticky • The other situation where an expectation may not be sticky is when it's in a sequence • As soon as another expectation that comes after it in the sequence has been used, it automatically retires
  • 40. Uninteresting Calls • In Google Mock, if you are not interested in a method, just don't say anything about it • If a call to this method occurs, you'll see a warning in the test output, but it won't be a failure
  • 41. Appendix - Mocks and fakes • Fakes implement the same interface as the object that they represent and returning pre- arranged responses • Mocks do a little more. They will examine the context of each call  Checking the order in which its methods are called.  Performing tests on the data passed into the method calls as arguments.
  • 42. Appendix - Mocks and fakes • Fake objects have working implementations, but usually take some shortcut (perhaps to make the operations less expensive), which makes them not suitable for production. An in-memory file system would be an example of a fake. • Mocks are objects pre-programmed with expectations, which form a specification of the calls they are expected to receive