I inject a dependency in some class. This class stores the dependency with an std::unique_ptr
and is therefore the only owner of the object.
What is the right way to mock a method in this dependency? My current solution is to get a raw pointer from the unique_ptr
before I hand over ownership. While this works, I think there are better ways to do it. What are they?
class Dependency
{
public:
virtual int plusOne(int x) {return x+1;}
};
class Dependency_Mock : public Dependency
{
public:
MOCK_METHOD1(plusOne, int(int));
};
class SomeClass
{
public:
void inject(std::unique_ptr<Dependency> dep) {dependency = std::move(dep);}
int execute(int x) {return dependency->plusOne(x);}
private:
std::unique_ptr<Dependency> dependency;
};
TEST(SomeClassTest, executeTestWithMock)
{
SomeClass some;
auto dep = std::make_unique<Dependency_Mock>();
auto& dep_ref = *(dep.get()); // This is kind of ugly.
some.inject(std::move(dep));
EXPECT_CALL( dep_ref , plusOne(_))
.WillOnce(Return(5));
EXPECT_EQ(some.execute(5), 5); // execute
}