Gmock Introduction to White Box testing

Source: Internet
Author: User

First, what is Gmock?

Gmock is an open-source white-box test tool launched by Google. Gmock is a very powerful thing, when testing a module, it may involve interacting with other modules, which can mock up the interface between the modules and simulate the interactive process. Its role is similar to the concept of piling in white box testing.

The following is a brief talk about the importance of piling in white box testing:

1, such as banking business, need to test business modules. At this point, it is impossible to operate a real database, and building a new database can be complex or time-consuming. Then you can use Gmock to simulate database operation by piling the database interface locally.

2, for example, to test a module, a module must be called the B module function. If the B module is not yet implemented, you can use Gmock to pile some interfaces of the B module. This allows the test of the a module to continue.

3, such as gateway equipment, when using Gtest test device module, must have the real equipment to let the test go on. If you use Gmock to simulate a set of SDK interfaces, you can keep the test going without the need for a real device. (This section is for internal reading only).

Second, how to obtain Gmock

Gmock is Google's Open source tool, Google's official website can download the source code. However, the company's internal staff can go up to 0.2 to fetch, in the "Research and Development Quality Department" folder. The latest version of Gmock is 1.7.0. Download the compressed package name "Gmock-1.7.0.zip". After decompression, the following:

Careful observation found that the compressed package contains Gtest folder, the folder is the source of gtest. For the most part, Gmock is used in conjunction with Gtest for white-box testing. For an introduction to Gtest's engineering, please see other articles on this blog.

This article briefly discusses Gmock compilation under Windows, Project-related files in the Msvc folder. Msvc folder is divided into 2005 and 2010 folders, respectively, with VS2005 and VS2010 set up the project.

Open the project with VS2010 and compile directly. After compiling the pass, you will get gmock.lib,gmock_maim.lib,gmock_test.ext three files. One of the gmock.lib is the library file we need, the other two works of this article is not to be elaborated.

Third, Gmock's first demo

We'll simulate the bank transfer system for the moment. The bank transfer system involves two operations of the database, first to find the account information through the bank card ID (including the account balance, etc.), and then in the calculation, the amount after the transfer of funds to the transfer parties. This completes the simple Bank transfer business.

Let's look at the mock (mock) database of the query account and write the amount of two methods, define a header file AccountManager.h:

//AccountManager.h//The interface of external services which should be mocked//Service interfaces that need to be mocks #pragmaOnce#include<string>#include"Account.h"  classAccountmanager { Public:      //use the account number to find the corresponding user    VirtualAccount Findaccountforuser (ConstSTD::string& userId) =0; //Update the user's information here    Virtual voidUpdateaccount (Constaccount& account) =0; }; 

Accountmanager is a class that needs to be mock (simulated). where Findaccountforuser (find the corresponding user) and Updateaccount (update account information) is the two ways to mock the transfer. Note that the two methods here are pure virtual functions. Because these two methods do not need to be implemented, the program will go to the mock function when testing, even if it is implemented, it will not be called.

Here are two ways to mock (simulate) Accountmanager by Gmock:

  class public accountmanager  {  public: Mock_       METHOD1 (Findaccountforuser, account (const std::string&));      void (const account&));  

The class Mockaccountmanager is inherited from the database db method class Accountmanager. Where MOCK_METHOD1 is defined as a macro for gmock. There are other similar macro definitions in the header file, such as mock_method0,mock_method2 ...

Mock_method#1 (#2, #3 (#4))

#2是你要mock的方法名称! #1表示你要mock的方法共有几个参数, #4是这个方法具体的参数, #3表示这个方法的返回值类型. It's simple, isn't it?!

//Account.h//Basic Application Data class #pragmaOnce#include<string>classAccount {Private: std::stringAccountId;//Account Number         LongBalance//deposit, uh, just call the balance.  Public: Account (); Account (ConstSTD::string& AccountId,Longinitialbalance); //Consumer    voidDebitLongamount); //Income    voidCreditLongamount); //get a deposit    LongGetBalance ()Const; //Get AccountSTD::stringGetaccountid ()Const; }; 

The above class is an account class that is designed to facilitate the structuring of money transfer operations. There are four ways to account for debit (consumption), credit (income), getbalance (get Deposits) and Getaccountid (get accounts).

//A Facility Class acts as an external DB classAccounthelper {Private: Std::map&LT;STD::string, account>Maccount; //An internal map to store all Accounts for test  Public: Accounthelper (Std::map&LT;STD::string, account>&maccount); voidUpdateaccount (Constaccount&Account ); Account Findaccountforuser (ConstSTD::string&userId);  }; Accounthelper::accounthelper (Std::map&LT;STD::string, account>&Maccount) {      This->maccount =Maccount; }  voidAccounthelper::updateaccount (Constaccount&Account ) {      This->maccount[account.getaccountid ()] =Account ; } Account Accounthelper::findaccountforuser (ConstSTD::string&userId) {     if( This->maccount.find (userId)! = This-maccount.end ())return  This-Maccount[userid]; Else         returnAccount (); } 

The above class, plays the role of the database. Mock (simulated) methods will be implemented using the function substitution of this class.

Next, let's write a test case to see the magical effect of gmock.

//test Case to test AccountserviceTEST (accountservicetest, transfertest) {Std::map&LT;STD::string, account>Maccount; maccount["A"] = account ("A", the); maccount["B"] = account ("B", -);     Accounthelper Helper (Maccount); Mockaccountmanager* Pmanager =NewMockaccountmanager (); //Specify the behavior of Mockaccountmanager//Always invoke Accounthelper::findaccountforuser//When Accountmanager::findaccountforuser is invokedExpect_call (*Pmanager, Findaccountforuser (testing::_)). willrepeatedly (Testing::invoke (&helper, &accounthelper::findaccountforuser)); //Always invoke Accounthelper::updateaccount//When Accountmanager::updateaccount is invokedExpect_call (*Pmanager, Updateaccount (testing::_)). willrepeatedly (Testing::invoke (&helper, &accounthelper::updateaccount)); Accountservice as; //inject the Mockaccountmanager object into Accountservice     as. Setaccountmanager (Pmanager); //operate Accountservice     as. Transfer ("A","B",1005); //Check the balance of account ("A") and Account ("B") to//Verify that Accountservice have done the right jobExpect_eq (1995, Helper.findaccountforuser ("A"). GetBalance ()); Expect_eq (3005, Helper.findaccountforuser ("B"). GetBalance ()); DeletePmanager; } 

First, declare an instance of a class Mockaccountmanager Pmanager, declaring an implementation class Accounthelper instance helper. The role of Expect_call is to replace the call Pmanager method with the corresponding method of implementing the helper. Here, replace the Pmanager Findaccountforuser method with the helper Findaccount method and replace the Pmanager Updateaccount method with the helper Updateaccount method.

Finally, we use Gtest's assertion mechanism expect_eq to judge the result.

Gmock Introduction to White Box testing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.