To effectively benefit from unit tests it is frequently necessary to optimise production code. The following sections show some of the possibilities. The common pattern is as usual to delegate the detailed work to a helper class which is appropriately instantiated.
Some of the following approaches have the drawback to weaken the protection of your class members. You have to decide yourself if this is acceptable for you.
But you should keep in mind that mechanisms like protected or private only defend from Murphy (unintentional usage) and not from Machiavelli (evil abuse). A potential attacker can simply copy a class declaration, remove all private and protected keywords and then access everything by doing a simple typecast. C++does not have run-time protection.
Sometimes you need predictable time values. Either you want to
minimise the impact of timeouts in error conditions or prevent idle times.
mockpp contains a sample implementation of how
to handle calls to
std::time(). This only covers
a resolution of 1 second. If you need a more sophisticated solution you
have to create your own code similar to this example. See the sources and
// prototype for the method under test: void myTimedMethod(TimeServer *time); // in production code: RealTimeServer rt_server; myTimedMethod(&rt_server); // in test code: MockTimeServer mock_server; mock_server.addUnixTime(0x123456); myTimedMethod(&mock_server);