I find myself often in the situation where I want to mock a non-copyable object, for example a DbHandle handle.
I was going back and forth looking at different design choices, and I settled on the following design:
In my production code, there is no need for a client of the Repository to know the DbHandle object, but for the unit tests, this DbHandle object is exactly the one I want to mock.
I settled for unique_ptr because they make clear that the Respository owns the DbHandle, even if it is created outside.
#include <memory>
class Repository {
public:
Repository() : d_dbHandel(std::unique_ptr<DbHandel>(new DbHandle("default"))) {
d_dbHandel->open("myDB");
}
Repository(std::unique_ptr<DbHandle> DbHandle) :
d_dbHandel(std::move(DbHandle) {
}
inline DbHandle& getDbHandel() {
return *d_dbHandel;
}
private:
std::unique_ptr<DbHandel> d_dbHandel;
};
What are some of the flaws of this approach?
DBHandleobject (but no other functionality), which by your own admission is not even needed.