How to write tests for classes relying on the operating system - c++

I have written a class that enumerates over the operating system's physical displays, retrieving their information and capabilities. I actually would like to test that this class works appropriately and embrace (unit) tests in general.
However, I have no idea how I would go about testing this class. Leaving the implementation details aside, it's basically defined as so:
class VideoMode {
public:
int64 width;
int64 height;
std::vector<int64> frequencies;
}
class Display {
protected:
std::vector<VideoMode> modes_;
std::string display_name_;
std::string adapter_name_;
bool primary_;
public:
Display(char* osDevName, char* osAdapterDevName);
// typical getters
}
How would I go about testing something that is so deeply integrated and dependent on the OS, and the physically attached hardware. I understand that writing an unit test for a class like this is difficult, so what alternatives do I have?

You should unit-test your class, not the os/external library functions.
You may add a facade layer which allows to mock those method. (That layer would not be unit tested by your UTs).
Something like:
class IOsVideoModeRetriever
{
public:
virtual ~IOsVideoModeRetriever() = default;
virtual std::vector<VideoMode> RetrieveVideoModes(/*...*/) = 0;
// ...
};
// CLass with implementation of OS specific functions
class OsVideoModeRetriever : public IOsVideoModeRetriever
{
public:
std::vector<VideoMode> RetrieveVideoModes(/*...*/) override;
// ...
};
// Class for UT
class OsVideoModeRetrieverMock : public IOsVideoModeRetriever
{
public:
MOCK(RetrieveVideoModes(/*...*/)); // Mock according to your framework
// ...
};
And your other class use it something like:
class Foo
{
public:
explicit Foo(IOsVideoModeRetriever&);
private:
IOsVideoModeRetriever& mOsVideoModeRetriever; // Or use `shared_ptr`
// depending of life time guaranty
};
Now you can test Foo.
You indeed would have problems if the os specific functions doesn't behave as you expected (Format of result, limitation to handle, edge case, ...), that should be limited to implementation part and not the interface.

First step: don't unit test not the interface with the OS, but the rest of the code. There is some code there; not much, but some.
Create an even lower API that your nice C++ interface talks to; it mimics a C style API your OS probably provides, even if it is a C++ class.
Like
struct OSDisplayInterface {
virtual ~OSDisplayInterface() {}
virtual std::size_t GetDisplayName( char const* name, char const* adapter, char* name, std::size_t name_buf_len ) = 0;
virtual bool IsDisplayPrimary( char const* name, char const* adapter ) = 0;
virtual bool GetVideoModeCount( char const* name, char const* adapter, std::size_t* mode_count ) = 0;
struct video_mode {
int64 width, height, frequency;
};
virtual bool GetVideoMode( char const* name, char const* adapter, std::size_t n, video_mode* mode ) = 0;
};
Or something that matches your lower level API as directly as you can. The idea is that this code should only fail in the real case if the OS's API fails.
Then test your C++ code against that, with fake OS video mode sets.
If you want to go further, this is basically outside of unit tests, but you can test either the above "OS display interface" or directly test your class against the OS.
To do this, however, you'll need a bunch of different hardware configurations.
Start with a farm of test machines you can remote-deploy code to and get results back.
Deploy your code, isolated from the rest of your code base, to those machines.
Each machine has an identifier on it.
Build a machine-identifier to test-results table.
Test against that. Ensure that when run on system "bob37", you get the right set of resolutions and the like.
Then, when an OS upgrade hits and the API is deprecated, you get an immediate red flag. (Of course, you also get red flags when a new driver is patched that gives new frequencies)
Unit test harness looks up the machine identifier, runs your code, and confirms the test results match.
Automate the deployment of the code to said machines so you can run the test on dozens of hardware platforms on a code change.
This is at best at the border of "unit testing". But you could imagine being in the middle of porting the OS-interface code to a new OS, environment or hardware, and running into problems that this would catch.

Related

How to test RDMA code without actual hardware?

I have C++ code which makes use of infiniband verbs for RDMA communication. I need to unit test this code, and thus, the function calls related to RDMA such as ibv_get_device_list() need to succeed without any actual hardware. From my understanding, I can do the following:
Create my own definition of each function to return the desired value, and link to this custom definition instead of infinband/verbs.h during testing. - Turning out to be very tedious
Create an interface and provide real and fake implementations of each function. The real one would simply call the infiniband verbs. - Can't do this as it would require too many changes to the original code
Use Soft-RoCE - I need to use the same machine as both the client and server, which I haven't been able to do
Would it be possible to use gmock to mock these functions? What other options can I consider?
Number 2 is the way to go. I'm going to challenge this statement:
Can't do this as it would require too many changes to the original code
If all goes well, your IDE has a "global search and replace" that can be used.
Let's fine the easiest way to abstract out your code with a minimal amount of disruptive changes:
Start by defining a class that simply wraps those C library function calls:
class RDMA
{
public:
virtual struct ibv_device **ibv_get_device_list(int *num_devices)
{
return ::ibv_get_device_list(num_devices);
}
virtual void ibv_free_device_list(struct ibv_device **list)
{
return ::ibv_free_device_list(list);
}
virtual uint64_t ibv_get_device_guid(struct ibv_device *device)
{
return ::ibv_get_device_guid(device);
}
};
Extend the above class with any other related calls you might need.
At global scope, declare an instance of the above class and a pointer to it:
RDMA g_product_code_rdma;
RDMA* g_ptrRMDA = &g_product_code_rdma;
Replace all your product code calls to the ibv functions to call through to the class via the global pointer. That is, change this:
ibv_free_device_list(&list);
to be invoked as:
g_ptrRMDA->ibv_free_device_list(&list);
Alternatively, you could declare helper functions:
ibv_device **global_ibv_get_device_list(int *num_devices)
{
return g_ptrRDMA->ibv_get_device_list(num_devices);
}
And then replace all your calls to use the new "global" version. A simple sed\awk script or just use your IDE to globally search and replace those function calls would be the easiest approach.
At this point, your product code functions the same as before.
in your unit tests, you simply declare a MockRDMA class that inherits from the RDMA class above.
class MockRDMA : public RDMA
{
public:
ibv_device **ibv_get_device_list(int *num_devices) override
{
// return a fake list of devices
}
virtual void ibv_free_device_list(struct ibv_device **list) override
{
return;
}
virtual uint64_t ibv_get_device_guid(struct ibv_device *device) override
{
return 0x012345678;
}
};
Then you just say this at the start of your unit tests:
MockRDMA mock;
g_ptrRDMA = &mock;
Example:
bool test_that_thing()
{
RDMA* original = g_ptrRDMA;
MockRDMA mock;
g_ptrRDMA = &mock;
// test code to validate the code that depends on those RDMA calls
// restore the RDMA class
g_ptrRDMA = original;
return result;
}
If you do decide to go for option 3 (SoftRoCE), it is certainly possible to have the client and server on the same host. You can try a Vagrant box I have created to make it easy to test SoftRoCE in a VM.

A program has many systems (class). Enable system to call others by class name?

Suppose that I have a game engine.
Let's say it contains class Graphic, GamePlay, and Physics system.
(The real case are 20+ systems.)
All 3 of them are derived from System.
This is a draft of the simple initialization.
main(){
Game_Engine* engine = new Game_Engine();
Graphic* sys1= new Graphic(engine); //set to System::engine_pointer
GamePlay* sys2= new GamePlay(engine);
Physics* sys3= new Physics(engine);
engine->addSystem(sys1); //add to Game_Engine's hash map
engine->addSystem(sys2);
engine->addSystem(sys3);
}
Then, I want to make all system can call each other.
Ex. Graphic can call GamePlay.
So I design the addSystem() as :-
class Game_Engine {
std::unordered_map<std::type_index,Sys*> hashTable;
void addSystem (System* system){
hashTable.add( std::type_index(typeid(*system)), system );
}
template <class SysXXX> SysXXX* getSystem(){
return hashTable.get(std::type_index(typeid(SysXXX)) );
}
}
The result is that each System can call each other by using only class name :-
class Graphic : public System {
void call_me_every_time_step(){
engine_pointer->getSystem<GamePlay>()->... do something ;
}
}
Now, it works as I wished, but
I heard that typeid is bad for performance.
Game_Engine.h now has to #include all Graphic.h, GamePlay.h and Physics.h, so compilation time increases.
(I tried to not include them -> typeid of 3 derived System will return wrong result.)
Is it possible to avoid those drawback? How?
Are there any other disadvantage?
Is this a bad design in the first place? If so, what is a good design?
(because I have very limited experience on C++.)
Edit 1 : Below section responses to gudok's answer
Adding a certain get/set function for each system is what I did.
However, I realized that it become harder to manage when there are more systems, at least for me.
I ran away from it and use the template code instead, as above.
For gudok's solution, a single system will increase programmer's work as followed:-
add the field declaration in the "GameEngine"
add another function to return a certain system
when rename a class e.g. "Graphics" to "Render" by using automatic refactor tool, I have to rename the getGraphics() to getRender() too (to make code readable)
Comparing the code in the question, a single system cost only 1 line.
engine->addSystem(new Graphics(engine));
It is not so trivial, especially when most systems are changing name, and amount of systems are increasing constantly.
Edit 2 : Response to gudok's enhanced answer
Make the GameEngine derived from SystemHolder{T} can reduce the work per System to 2 places :-
: public SystemHolder<Graphics>
and
engine.addSystem<Graphics>(new Graphics());
It is still 2 places, though.
The code in question uses only 1 place.
Therefore, it is not good enough, but thank for trying!
What is the reason to use hash map and typeids instead of storing each of systems separately in GameEngine? Semantically, all these systems do different things. I'd rather do following:
class GameEngine {
std::vector<System*> systems;
Graphics* graphics;
Gameplay* gameplay;
Physics* physics;
void setGraphics(Graphics* graphics) {
this->graphics = graphics;
this->systems.push_back(graphics);
}
Graphics* getGraphics() {
return this->graphics;
}
...
};
The idea behind this solution is that:
Each of systems is different from semantical point of view. When you access graphics from somewhere, most likely you will use functions specific to Graphics and not functions universal for all Systems. Storing each of systems separately removes necessity for typeids and unnecessary type conversions.
When you need to handle all systems in some uniform way (for example, advancing game time), you use systems field:
for (auto it = systems.begin(); it != systems.end(); it++) {
it->tick();
}
EDIT Here is enhanced solution. You add new system by additionally inheriting GameEngine from SystemHodler. Getting and setting instances of particular System is uniform by using getSystem<T> and setSystem<T> methods -- as you wanted.
#include <vector>
class System {
public:
virtual ~System() {}
};
class Graphics : public System {};
class Physics: public System {};
template<typename T>
class SystemHolder {
public:
T* getSystem() { return system; }
void setSystem(T* system) { this->system = system; }
private:
T* system;
};
class GameEngine: public SystemHolder<Physics>, public SystemHolder<Graphics> {
public:
template<typename T>
inline void addSystem(T* system) {
systems.push_back(system);
SystemHolder<T>::setSystem(system);
}
template<typename T>
inline T* getSystem() {
return SystemHolder<T>::getSystem();
}
private:
std::vector<System*> systems;
};
int main(int argc, char* argv[]) {
GameEngine engine;
engine.addSystem<Physics>(new Physics());
engine.addSystem<Graphics>(new Graphics());
engine.getSystem<Physics>();
engine.getSystem<Graphics>();
}

How to create a loose coupling between parts of a project?

Introduction:
I come from a mechanical engineering background, but took a class in embedded software programming (on a lovely little robot) with the intention of improving some skills I had in programming already. However, the class was largely unsatisfactory in what I hoped to achieve (basically, it taught the basics of c++ with some very superficial composition patterns).
Question We were told to make our code somewhat object oriented by defining classes for various parts of the code. Since all the parts were very dependent of each other, the general structure looked as follows (basically, a Drive, Sensors and WorldModel class with some dependencies, and a Director class trying to make our robot solve the task at hand)
class Drive{
void update();
Drive(Sensors & sensors);
private:
Sensors & sensors
};
class Sensors{
void update();
}
class WorldModel {
void update();
WorldModel(Sensors & sensors, Drive & drive);
private:
Sensors & sensors;
Drive & drive;
};
class Director {
void update();
Director(Sensors & sensors, Drive & drive, WorldModel & worldmodel);
private:
Sensors & sensors;
Drive & drive;
WorldModel & worldmodel;
};
This is actually an extremely condensed version. It seems to me however that this is not really object oriented code as much as Clumsily Split-Up Codeā„¢. In particular, it seemed almost impossible to make e.g. the Sensors class get data from the Drive class without some fudging around in the Director class (i.e., first perform a function in the Drive class to get the velocity setpoint, and then provide that to the update() method in the Sensors class to do some Kalman filtering).
How does one create a project in c++ with various parts being very dependent on each other, without this becoming a problem? I read an SO answer on interfaces but I'm not sure how to apply that to this problem - is that even the way to go here? Is there a design pattern (not necessarily an object oriented one) that is suitable for projects such as this one?
No, there's not a design pattern for projects "like this".
Design patterns are not the goal.
So, let me put a few guesses straight:
you want light weight code (because otherwise you'd be using Java, right)
you want maintainable code (because otherwise, spaghetti would be fine)
you want idiomatic code
Here's what I'd do:
declare classes in separate headers
use forward defines to reduce header coupling
move implementations in the corresponding source files
keep unwanted implementation dependencies out of the header file. Optionally use the Pimpl Idiom here.
e.g. if you use library X to implement Y::frobnicate don't include libX.h in your Y.h. Instead, include it in Y.cpp only.
If you find that you need class member declaration that would require libX.h in the header, use the Pimpl Idiom.
I don't know what else you could want here :)
Maybe, if you need "interfaces" consider using template composition. Policy, strategy, state patterns. E.g. Instead of
#include <set>
struct ISensors {
virtual int get(int id) const = 0;
virtual int set(int id, int newval) const = 0;
virtual std::set<int> sensors() const = 0;
};
class Drive {
void update();
Drive(ISensors &sensors);
private:
ISensors &sensors;
};
You could consider
template <typename Sensors>
class Drive {
void update();
Drive(Sensors &sensors);
private:
Sensors &sensors;
};
Which leaves you free to implement Sensors in any which way that statically compiles. The "limitation" is that the injection of dependencies needs to be statically defined/typed. The benefit is ultimate flexibility and zero-overhead: e.g. you couldn't have virtual member function templates, but you can use this as a Sensors policy:
struct TestSensors {
int get(int) { return 9; }
int set(int, int) { return -9; }
template<typename OutputIterator>
OutputIterator sensors(OutputIterator out) const {
int available[] = { 7, 8, 13, 21 };
return std::copy(std::begin(available), std::end(available), out);
}
};
using TestDrive = Drive<TestSensors>;

Inheritance hierarchy vs. multiple inheritance (C++)

Well, I was thinking about a design decision for the past few days and since I still cannot favor one over the other I thought maybe someone else has an idea.
The situation is the following: I have a couple of different interface classes abstracting several communication devices. Since those devices differ in their nature they also differ in the interface and thus are not really related. Lets call them IFooDevice and IBarDevice. More device types may be added over time. The language is C++.
Since other components (called clients from now on) might want to use one or more of those devices, I decided to provide a DeviceManager class to handle access to all available devices at runtime. Since the number of device types might increase, I would like to treat all devices equally (from the managers point of view). However, clients will request a certain device type (or devices based on some properties).
I thought of two possible solutions:
The first would be some kind of interitance hierarchy. All devices would subclass a common interface IDevice which would provide the (virtual) methods necessary for management and device query (like getProperties(), hasProperties(), ...). The DeviceManager then has a collection of pointers to IDevice and at some point a cast from Base to Derived would be necessary - either with a template method in the manager or after the request on the client's side.
From a design point of view, I think it would be more elegant to seperate the concerns of managing a device and the interface of the specific device itself. Thus it would lead to two unrelated interfaces: IManagedDevice and e.g. IFooDevice. A real device would need to inherit from both in order to "be" of a specific device type and to be managaeble. The manager would only manage pointers to IManagedDevice. However, at some point there will be the need to cast between now unrelated classes (e.g. from IManagedDevice to IFooDevice) if a client wants to use a device provided by the manager.
Do I have to choose the lesser of two evils here? And if so which one would it be? Or do I miss something?
Edit:
About the "managing" part. The idea is to have library providing a variety of communication devices different (client) applications can use and share. Managing merely comes down to the storage of instances, methods for registering a new device and looking up a certain device. The responsibility for choosing the "right" device for the task is up to the client side because it knows best which requirements it puts on the communication. In order to reuse and thus share available devices (and by that I mean real instances and not just classes) I need a central access point to all available devices. I'm not too fond of the manager itself but it's the only thing I could come up to in that case.
I think the visitor pattern is a better choice for this.
I think what Tom suggested might be altered a bit to suit your needs:
class IManagedDevice
{
IDevice* myDevice;
/* Functions for managing devices... */
};
In this case IDevice is an empty interface that all devices inherit from. It gives no real benefit, just make the class hierarchy handling slightly more bearable.
Then, you can have then ask for the specific device (IFooDevice or IBarDevice), probably via some sort of device type ID.
If all you need is to have a common code to manage the devices, and then pass each device to the appropriate place I think you can get away with something like this:
class IDevice
{
virtual void Handle() = 0;
};
class IFooDevice : public IDevice
{
virtual void Handle()
{
this->doFoo();
}
virtual void doFoo() = 0;
}
class IBarDevice : public IDevice
{
virtual void Handle()
{
this->doBar();
}
virtual void doBar() = 0;
}
With the manager calling the Handle function.
I think I'd go for a simple solution of having a base class for Device that takes care of registering the device in the global device list and then static methods for looking them up. Something like:
struct Device
{
static Device *first; // Pointer to first available device
Device *prev, *next; // Links for the doubly-linked list of devices
Device() : prev(0), next(first)
{
if (next) next->prev = this;
first = this;
}
virtual ~Device()
{
if (next) next->prev = prev;
if (prev) prev->next = next; else first = next;
}
private:
// Taboo - the following are not implemented
Device(const Device&);
Device& operator=(const Device&);
};
Then you can just derive all devices from Device and them will be automatically placed in the global list on construction and removed from the global list on destruction.
All your clients will be able to visit the list of all devices by starting from Device::first and following device->next. By doing a dynamic_cast<NeededDeviceType*>(device) clients can check if the device is compatible with what they need.
Of course any method that is implemented in every device type (e.g. a description string, a locking method to ensure exclusive use by one client and the like) can be exported also at the Device level.
when communicating with devices I separated the the device and the communication manager completely.
I had a simple communication manager that was based on Boost.Asio. The interface was something like
/** An interface to basic communication with a decive.*/
class coms_manager
{
public:
virtual
~coms_manager();
/** Send a command. */
virtual
void
send(const std::string& cmd) = 0;
/** Receive a command.
* #param buffsize The number of bytes to receive.
* #param size_exactly True if exactly buffsize bytes are to be received. If false, then fewer bytes may be received.
*/
virtual
std::string
recv( const unsigned long& buffsize = 128,
const bool& size_exactly = false) = 0 ;
/** Timed receive command.
* #param buffsize The number of bytes to receive.
* #param seconds The number of seconds in the timeout.
* #param size_exactly True if exactly buffsize bytes are to be received. If false, then fewer bytes may be received.
*/
virtual
std::string
timed_recv( const unsigned long& buffsize = 128,
const double& seconds = 5,
const bool& size_exactly = false) = 0;
};
I then implemented this interface for tcp (ethernet) and serial communications.
class serial_manager : public coms_manager {};
class ethernet_manager : public coms_manager {};
Each of the devices then contained (or pointed to) (rather than inherited) a coms_manager object
For example:
class Oscilloscope
{
void send(const std::string& cmd)
{
m_ComsPtr->send(cmd);
}
private:
coms_manager* m_ComsPtr;
};
You can then swap around the communication method by changing what the pointer points to.
For me, this didn't make much sense (the Oscilloscope was EITHER attached via serial OR via ethernet and so I actually opted for
template<class Manager>
class Oscilloscope
{
void send(const std::string& cmd)
{
m_Coms.send(cmd);
}
private:
Manager m_Coms;
};
and I now use
Oscilloscope<serial_manager> O1(/dev/tty1); // the serial port
Oscilloscope<ethernet_manager> O2(10.0.0.10); //The ip address
which makes more sense.
As for your suggestion as to have a generic device interface. I started with that too, but then wasn't sure of its utility - I always wanted to know exactly what equipment I was sending a command to, I neither needed nor wanted to work through an abstract interface.
At a first glance, the first approach seems fine for me if all devices need to be managed and no other stuff can be done with an unknown device. The meta data for a general device (e.g. name, ...) would typically be the data one need for managing devices.
However, if you need to separate the interface between the management and the device functionality, you can use virtual inheritance.
IManagedDevice and IFooDevice are both interfaces of the same concrete device, so they both have a common virtual base IDevice.
Concretely (run code):
#include <cassert>
class IDevice {
public:
// must be polymorphic, a virtual destructor is a good idea
virtual ~IDevice() {}
};
class IManagedDevice : public virtual IDevice {
// management stuff
};
class IFooDevice : public virtual IDevice {
// foo stuff
};
class ConcreteDevice : public IFooDevice, public IManagedDevice {
// implementation stuff
};
int main() {
ConcreteDevice device;
IManagedDevice* managed_device = &device;
IFooDevice* foo_device = dynamic_cast<IFooDevice*>(managed_device);
assert(foo_device);
return 0;
}

Elegant way of overriding default code in test harness

Let's say I have the following class:
class Foo
{
public:
Foo()
{
Bar();
}
private:
Bar(bool aSendPacket = true)
{
if (aSendPacket)
{
// Send packet...
}
}
};
I am writing a test harness which needs to create a Foo object via the factory pattern (i.e. I am not instantiating it directly). I cannot change any of the factory instantiation code as this is in a framework which I don't have access to.
For various reasons I don't want the Bar method to send packets when running it from a test harness.
Assuming I cannot call Bar directly (eliminating potential solutions like using a friend class), what is an elegant design pattern to use to prevent packets being sent out when running my test harness? I definitely don't want to pollute my production code with special cases.
You want Bar to send a packet in ordinary operation, but not in testing. So you will have to have some code which runs when you call Bar during testing, even if it's an empty function. The question is where to put it.
We can't see the code inside the if(aSendPacket) loop, but if it delegates its work to some other class then we can make the substitution there. That is, if the loop is
if(aSendPacket)
{
mPacketHandler.send();
}
so that the work is done by the `packetHandler class:
// packetHandler.cc
void packetHandler::send()
{
// do some things
// send the packet
}
then we can make a "mute" version of the packetHandler class. (Some would call it a stub or a mock class, but there seems to be somedebate about the definitions of these terms.)
// version of packetHandler.cc to be used when testing e.g. Foo
void packetHandler::send()
{
// do some things
// don't actually send the packet
}
When testing Foo, compile this version of packetHandler and link it in. The factory won't know the difference.
If, on the other hand, the code for sending a packet is spelled out in Foo, with no way to head off the behavior outside the Foo class, then you will have to have a "testing" version of Foo.cc (there are other ways but they are clumsy and dangerous), and the best way to do that depends on the details of your codebase. If there are only a couple of "untestable" features like this, then it's probably best to put Foo::bar(...) in a source file by itself, with two versions (and do the same for each of the other special methods). If there are many then may be worth deriving a factory class specific to testing, which will construct instances of, e.g. class testingFoo : public Foo which overrides Bar. After all, this is what the abstract factory design pattern is for.
I would view 'bar' as an algorithm to send data which follows a template method
// Automation Strategies
class AutomationStrategy{
public:
void PreprocessSend(bool &configsend) const {return doPreprocessSend(configsend);}
void PostprocessSend() const {return doPostprocessSend();}
virtual ~AutomationStrategy(){}
private:
virtual void doPreprocessSend(bool &configsend) const = 0;
virtual void doPostprocessSend() const = 0;
};
// Default strategy is 'do nothing'
class Automation1 : public AutomationStrategy{
public:
~Automation1(){}
private:
void doPreprocessSend(bool &configsend) const {}
void doPostprocessSend() const {}
};
// This strategy is 'not to send packets' (OP's intent)
class Automation2 : public AutomationStrategy{
public:
~Automation2(){}
private:
void doPreprocessSend(bool &configsend) const {
configsend = false;
}
void doPostprocessSend() const {}
};
class Foo{
public:
Foo(){
Bar();
}
private:
// Uses Template Method
void Bar(bool aSendPacket = true, AutomationStrategy const &ref = Automation1())
{
ref.PreprocessSend(aSendPacket); // Customizable Step1 of the algorithm
if (aSendPacket) // Customizable Step2 of the algorithm
{
// Send packet...
}
ref.PostprocessSend(); // Customizable Step3 of the algorithm
}
};
int main(){}
If you can't modify 'bar' interface, then configure 'Foo' to accept the test automation strategy in it's constructor and store it (to be later used while calling 'bar')
It might be a gross oversimplification, but my first inclination is to add some sort of testing conditions object (really a variable library) which defaults everything to false, then put hooks in the code where you want to deviate from standard behavior for testing, switching on the [effectively global] testing conditions object variables. You're going to need to do the equivalent logic anyway, and everything else seems either needlessly more complicated, more disruptive to understanding the logic flow inside the object, or more potentially disruptive to the behavior in the testing case. If you can get away with a minimal amount of conditional switch locations/variables, that probably the easiest solution.
My opinion, anyway.