I have a singleton class B
which contains a certain method RunTimer()
that I'd like to unit test which is a wrapper around an external utility. For unit test, I want to exclude the testing of the timer and rely on other parameters (not shown here)
Fake
is what I'd use in unit test which will contain additional ways for the sake of testing.
Since there's only ever a single instance of a Singleton, does the idea of switching out the std::unique_ptr<ITimer> _ptr
for Fake
in unit test make sense for the sake of testing?
class ITimer
{
public:
virtual void foo() = 0;
virtual ~Base() = default;
};
class Real : public ITimer
{
public:
void foo() override {}
};
// For unit test
class Fake : public ITimer
{
public:
void foo() override {}
};
class B
{
std::unique_ptr<ITimer> _ptr;
// default ctor creates a Real
B() : B(std::make_unique<Real>())
{
}
B(std::unique_ptr<ITimer> ptr) : _ptr(std::move(ptr))
{
}
public:
static B& get()
{
static B b;
return b;
}
void RunTimer()
{
Timer::Run(); // external utility
}
void change(std::unique_ptr<Base> ptr)
{
_ptr = std::move(ptr);
}
};
int main()
{
B::get(); // use Real in actual code
// use Fake - for testing (eventually to be in TEST_F())
auto mk = std::make_unique<Fake>();
B::get().change(std::move(mk));
// do testing on B::_ptr
}