The short answer is no, you can't do it unless you make some minor changes to your class.
EXPECT_CALL
requires access to the mock object:
EXPECT_CALL(mock_object, method_name(matchers...))
So how can you call it without any reference to mock_object
when it is a private member without any getters and no friends?
You do need to somehow provide external access to _bar
so that EXPECT_CALL
can use it to check your calls on _bar
.
There are several ways to do this, but they all require changing your code:
- Make
_bar
public
- Dependency injection
- Add a getter of
_bar
to Foo
- Make your test a friend of Foo
It's common to do this by dependency injection. For example, you can add a new constructor like this:
class Foo {
public:
Foo() : _bar(new Bar()) {}
Foo(Bar* bar) : _bar(bar) {}
int DoSomething(int a) { return _bar->f1(a); }
Bar *getBar() { return _bar.get(); } // Getter was added.
private:
std::unique_ptr<Bar> _bar;
};
And here is an example on how you can do this by adding a getter function to Foo
:
class Bar {
public:
MOCK_METHOD(int, f1, (int), ());
};
class Foo {
public:
Foo() : _bar(new Bar()) {}
int DoSomething(int a) { return _bar->f1(a); }
// A getter was added (Albeit not ideal since it exposes the raw pointer).
Bar *getBar() { return _bar.get(); }
private:
std::unique_ptr<Bar> _bar;
};
TEST(FooTest, TestBar) {
Foo foo;
EXPECT_CALL(*(foo.getBar()), f1(2)).WillOnce(Return(4));
auto result = foo.DoSomething(2);
EXPECT_EQ(result, 4);
}
Working example here: https://godbolt.org/z/1cdq7Po1T