I am attempting to write a mock for a class with a private vector that will insert data into the private vector. However, I am not seeing a way to do it with Google Mock. Ideally, I would like to not have anything related to testing in my interface. Also, I would not like to make the private vector protected and subclass the class and add an accessor method, as this would cause my code to leak its implementation.
Here's what I have so far. What I'm trying to accomplish is to insert data with the Fake class, and use the Mock class to Invoke Real::first() on the pointer to the class of Fake (so that I can use Fake's vector instead of Real's). 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;
}
Does anyone know what I'm doing wrong? Or is there an easier way to accomplish this?
Aucun commentaire:
Enregistrer un commentaire