How to access a private member on Google Mock

I am trying to write a layout for a class with a private vector that will insert data into a private vector. However, I see no way to do this using Google Mock. Ideally, I would not want to have anything to do with testing in my interface. In addition, I would not want the private vector to protect and subclass the class and add the accessor method, as this could lead to code leakage.

Here is what I still have. What I'm trying to do is insert data into the Fake class and use the Mock class to call Real :: first () in the pointer to the Fake class (so that I can use Fake vector instead of Real). When this program is compiled, -1 is returned instead of 4.

#include <iostream>
#include <vector>
#include <gmock/gmock.h>

using namespace std;
//using ::testing::_;
using ::testing::Invoke;

class A {
protected:
    vector<int> a;

public:
    virtual int first() = 0;
    virtual ~A() {}
};

class Real : public A {
public:
    virtual int first() {
        cout << "size: " << a.size() << endl;
        return a[0];
    }
};

class Fake : public A {
public:
    virtual void insert(int b) {
        a.push_back(b);
        cout << a.size() << endl;
    }

private:
    virtual int first() { return -1; }
};

class Mock : public A {
public:
    Mock(Fake* c) :
        c_(c) {}

    MOCK_METHOD0(first, int());

    void delegate() {
        ON_CALL(*this, first())
            .WillByDefault(Invoke((Real*)c_, &Real::first));
    }

private:
    Fake* c_;
};

int main(void) {
    Fake c;
    c.insert(4);

    Mock z(&c);

    z.delegate();

    cout << z.first() << endl;
    return 0;
}

- , ? ?

+4
2

c, Mock, Fake, Real. Fake Real first() A, Fake first() , , first() Real.

, , ( ), , :

1

first A Fake:

class A {
protected:
    vector<int> a;

public:
    virtual int first() {
        return a[0];
    }

    virtual ~A() {}
};

class Fake : public A {
public:
    virtual void insert(int b) {
        a.push_back(b);
        cout << a.size() << endl;
    }
};

2

first Fake. , , Fake, .

class Fake : public A {
public:
    virtual void insert(int b) {
        a.push_back(b);
        cout << a.size() << endl;
    }

private:
    virtual int first() {
        return a[0];
    }
};

3

A first(), .

+1

, , , .

A mock .

class AStorage {
vector<int> vals;
};

class A {
AStorage& storage;

public:
A(AStorage& stor) :
storage(stor) {}
};

, A . , , , .

0

Source: https://habr.com/ru/post/1589341/


All Articles