GoogleMock for Dummies

Slides:



Advertisements
Similar presentations
11-Jun-14 The assert statement. 2 About the assert statement The purpose of the assert statement is to give you a way to catch program errors early The.
Advertisements

GoogleTest Primer. Outline Basic Concepts Assertions Basic Assertions Binary Comparison String Comparison Floating-Point Comparison Simple Tests Test.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 8 l Basic Exception Handling »the mechanics of exceptions l.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
1 Chapter Three Using Methods. 2 Objectives Learn how to write methods with no arguments and no return value Learn about implementation hiding and how.
Chapter 14: Overloading and Templates C++ Programming: Program Design Including Data Structures, Fifth Edition.
Computer Science 1620 Loops.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Slides prepared by Rose Williams, Binghamton University Chapter 9 Exception Handling.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
Exceptions Objectives At the conclusion of this lesson, students should be able to Explain the need for exceptions Correctly write programs that use.
Chapter 15: Operator Overloading
Unit Testing Using PyUnit Monther Suboh Yazan Hamam Saddam Al-Mahasneh Miran Ahmad
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and.
What is RobotC?!?! Team 2425 Hydra. Overview What is RobotC What is RobotC used for What you need to program a robot How a robot program works Framework.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
1 Exception Handling Introduction to Exception Handling Exception Handling in PLs –Ada –C++ –Java Sebesta Chapter 14.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 9 : Exception Handling King Fahd University of Petroleum & Minerals College of Computer.
Designing For Testability. Incorporate design features that facilitate testing Include features to: –Support test automation at all levels (unit, integration,
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
Dr. Tom WayCSC Testing and Test-Driven Development CSC 4700 Software Engineering Based on Sommerville slides.
Linked List. Background Arrays has certain disadvantages as data storage structures. ▫In an unordered array, searching is slow ▫In an ordered array, insertion.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
Using Mock Objects with Test Driven Development Justin Kohlhepp
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Copyright 2006 Oxford Consulting, Ltd1 February Polymorphism Polymorphism Polymorphism is a major strength of an object centered paradigm Same.
CMP-MX21: Lecture 5 Repetitions Steve Hordley. Overview 1. Repetition using the do-while construct 2. Repetition using the while construct 3. Repetition.
Mock objects.
1 CS161 Introduction to Computer Science Topic #9.
CMSC 202, Version 3/02 1 Copy Constructors and Overloaded Assignment.
Computer Programming with JAVA Chapter 8. Exception Handling Basic Exception Handling the mechanics of exceptions Defining and Using Exceptions some "simple"
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Function Overloading and References
Methods Methods are how we implement actions – actions that objects can do, or actions that can be done to objects. In Alice, we have methods such as move,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Overview of C++ Polymorphism
Fun fun ’til daddy takes your C turbo away! A C program is organized into one or more modules (source files created by a programmer), within which are.
Chad’s C++ Tutorial Demo Outline. 1. What is C++? C++ is an object-oriented programming (OOP) language that is viewed by many as the best language for.
Google C++ Testing Framework Part 2: Assertion. Concepts A test case contains one or many tests. ◦ You should group your tests into test cases that reflect.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
Windows Programming Lecture 06. Data Types Classification Data types are classified in two categories that is, – those data types which stores decimal.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
Powerpoint Templates Page 1 Powerpoint Templates Unit Testing Ari Seppi
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Introduction To Repetition The for loop
Java Programming Language
Why exception handling in C++?
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
Introduction to Functions
Exception Handling Chapter 9.
Testing and Test-Driven Development CSC 4700 Software Engineering
CISC101 Reminders Assn 3 due tomorrow, 7pm.
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
Designing For Testability
CISC101 Reminders Assignment 3 due today.
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions.
Presentation transcript:

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: Use some simple macros to describe the interface you want to mock, and they will expand to the implementation of your mock class Create some mock objects and specify its expectations and behavior using an intuitive syntax 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: Derive a class MockTurtle from Turtle. Take a virtual function of Turtle. Count how many arguments it has. Inside the child class, write MOCK_METHODn()/MOCK_CONST_METHODn();, where n is the number of the arguments. Cut-and-paste the function name as the first argument to the macro, and leave what's left as the second argument. 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: Import the Google Mock names from the testing namespace such that you can use them unqualified. Create some mock objects. Specify your expectations on them (How many times will a method be called? With what arguments? What should it do? etc.). 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. When a mock is destructed, Google Mock will automatically check whether all expectations on it have been satisfied.

Our painter object will use Turtle object to do the drawing. 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? 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 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 Invoke pre-defined function See http://code.google.com/p/googlemock/wiki/CheatSheet#Actions

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