I have a library class that I need to mock in one of my tests, and the object that accepts it takes a unique_ptr
to one. After reading this answer, I assumed I could just do something like this.
class LibraryClassMock : public LibraryClass {
public:
MOCK_METHOD0(do, void());
};
TEST(ProxyServiceTest, RequestMade) {
auto mock = std::make_unique<LibraryClassMock>();
auto mockPtr = mock.get();
// Setup mock
EXPECT_CALL(*mockPtr, do()).Times(1);
// Signature of constructor is MySerivce(std::unique_ptr<LibraryClass>)
MyService service{std::move(mock)};
proxyService.runCommand("cmd");
}
Unfortunately, LibraryClass
does not have a virtual destructor (nor can I add one), and because MyService
holds a pointer of the form unique_ptr<LibraryClass>
, this scope ending causes a leak (as the mock's destructor is not called). Without reworking Service
to accept a shared_ptr
, is there a way to work around this? In my application, service
should be controlling the lifetime of the object passed in, but I need to mock it for my test.