1.Simple google test EXPECT call example with one call of the tested function
tested code
1 2 3 4 5 6 7 8 9 10 11 12 |
|
single EXPECT_CALL
1 2 3 4 5 6 7 8 9 10 11 12 |
|
As you can see above, we have one call of function my_func_int so there will be a certain call of mocked function GetValueInt, so the EXPECT_CALL for this function is mandatory.
Depending of the return value of this functions, we had to decide also if the function SetValue will be called. In this specific case, it is, so the EXPECT_CALL was used again for this function.
Pretty simple, let's see a more complex example.
2.Double call of the tested function and the solution for EXPECT_CALL
In the next example, we will call our tested function my_func_int twice (NOTE: we will do that only for training purpose, in this case there is no other reason to do that):
NOT WORKING multiple EXPECT_CALL
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
As you can see above, we changed the number of EXPECT_CALL for our mocked function GetValueInt, but this code will throw an error like this:
Output result (error)
|
The error above occurred because google test misinterprets the information which was given about all EXPECT_CALL. The way first two expect calls are used tells google test that there are two separated expect calls each called 1 time.
Actually there are two calls for the same function with same arguments, so an error is thrown.
I will show you below some examples how to write the expect calls so that there will be no errors:
Solution 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
Solution 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
Solution 3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
3.One more example
tested code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
As you can see above, our function my_func_int_2 calls GetValueInt multiple times, but with different arguments. We will use that in our advantage to write the test code:
Solution for my_func_int_2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
In this way, all EXPECT_CALL have also the information about arguments of the function GetValueInt, so google test now can make the difference between them.