Google test in CLion - Unit test function using gmock

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  bool bank::read1(int duration){
    int num_votes = take_vote(&party, leader, duration);
    if (num_votes > 0){
        int count_votes = read(dup, buffer, len);
        if( count_votes > 0){
            std::stringstream s;
            s << std::hex;
            for (int i = 0; i < count_votes; i++)
                 s  << static_cast<int>(buffer[i]);
            return true;
        }
        else{
            return false;
        }
    }
    else {
        if(num_votes == -10)
        return false;
    }
  }


I have a function which works well and I would like to unit test it. The function takes in duration of campaign, computes the number of votes num_votes. If number of votes is greater than 0, vote count count_votes (which is functionally different from num_votes) is read. If vote count is greater than 0, return true, otherwise return false.

There is a possibility that the number of votes might go till -10 and if it reaches -10, then return false. I would like to unit test this function. I understand I have to use mock for this. However, being new to gmock, I am not sure how I can implement. Below is the best I tried so far. Please let me where I am going wrong.

1
2
3
4
5
6
7
8
9
10
  TEST(test1, c1){
    bank* vote_bank = new bank();
    vote_bank::num_votes = 5;
    vote_bank::count_votes = 6;

    EXPECT_EQ(true, bank->read1(0));

    vote_bank::num_votes = -10;
    EXPECT_EQ(false, bank->read1(0));
  }
What is it that you want to mock?

I need to unit test the function. In order to do so, I suppose I might have to mock variables like num_votes and count_votes, am I correct in thinking that way? Or can I unit test them without mocking?
It doesn't make sense to mock a simple int. What interface does an int have, that you could write a mock for it?

I get the feeling you don't really understand what mocking is, or what it's used for. The wiki article looks like a good start, if you want to get a better understanding:

https://en.wikipedia.org/wiki/Mock_object

The Google Mock project itself also has a brief introduction:

https://github.com/google/googletest/blob/master/googlemock/docs/ForDummies.md

Last edited on
I think in its current state the function isn't testable since it depends on two external functions - take_vote and read.
To unit test you would need to mock these two functions.
For example if read were part of a class VoteReader and Bank had a member reader you could create a mock object, pass it to the bank object so for testing, the read1 method would call the read method of the mock object. Same procedure for take_vote.
Hope this makes any sense.

Topic archived. No new replies allowed.