C + + U n i t Te s t i n g
Stubs & Mocks
EXERCISE 图书馆管理员 (Librarian) 会定期向书商
(BookVendor) 购买一些书籍来充实图书馆 :
书商能够提供多种图书 ( 附有价格 ) 供管
理员进行选择
管理员仅会挑选当前图书馆中不存在的书
籍进行购买
管理员选好图书后 , 会向书商支付所选书
籍的总金额
2
EXERCISE 从原始 Repo 上更新代码
git remote add source https://github.com/
coney/cpp-unit-testing.git
git pull source master
重构 Librarian, 使管理员可以通过 store
方法存入一个 Book 对象
思考如何编写 Librarian::store(vendor)
的测试
3
MOCKING
With Google Mock
4
WHY GOOGLE MOCK
You want to "mock out" your dependencies.
Your tests are slow as they depend on too many libraries or
use expensive resources (e.g. a database).
Your tests are brittle as some resources they use are
unreliable (e.g. the network, current time).
You want to test how your code handles a failure which is
not easy to trigger.
You need to make sure that your module interacts with
other modules in the right way.
Dependent Interface Does not yet exist or may change
behavior.
5
MOCK OBJECT
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
6
EXPECTATIONS
Use the EXPECT_CALL() macro to set an
expectation on a mock method
7
ACTIONS
The return value of mock functions can be
specified by Will and Return Statement
8
USING GMOCK
include <gmock/gmock.h>
write your mocks and tests
initialize gmock by InitGoogleMock()
call RUN_ALL_TESTS() in main() function
compile and run
InitGoogleMock() will automatically initialize Google Test
9
EXERCISE 图书馆管理员 (Librarian) 会定期向书商
(BookVendor) 购买一些书籍来充实图书馆 :
书商能够提供多种图书 ( 附有价格 ) 供管
理员进行选择
管理员仅会挑选当前图书馆中不存在的书
籍进行购买
管理员选好图书后 , 会向书商支付所选书
籍的总金额
1
0
STUBS VS MOCKS
Behavior Based Verification
1
1
TEST DOUBLES
Dummy objects are passed around but never actually used.
Usually they are just used to fill parameter lists
Fake objects actually have working implementations, but
usually take some shortcut which makes them not suitable
for production
Stubs provide canned answers to calls made during the
test, usually not responding at all to anything outside
what's programmed in for the test
Mocks are objects pre-programmed with expectations
which form a specification of the calls they are expected to
receive
1
2
MATCHERS
When a mock function takes arguments, we
can specify the expected arguments value
testing::_ will match any input arguments
1
3
CARDINALITIES
Use the Times() to specify the cardinality as it
tells how many times the call should occur
1
4
EXERCISE 图书馆管理员 (Librarian) 会定期向书商
(BookVendor) 购买一些书籍来充实图书馆 :
书商能够提供多种图书 ( 附有价格 ) 供管
理员进行选择
管理员仅会挑选当前图书馆中不存在的书
籍进行购买
管理员选好图书后 , 会向书商支付所选书
籍的总金额
1
5
REFERENCE
https://
github.com/coney/cpp-unit-testing/tree/master/02-
GMock
https://
code.google.com/p/googlemock/wiki/ForDummies
https://
code.google.com/p/googlemock/wiki/CheatSheet
https://
code.google.com/p/googlemock/wiki/CookBook
https://
code.google.com/p/googlemock/wiki/FrequentlyAsk
1
6
THANK YOU
For questions or suggestions:
Wu Kun
[email protected]