Can anyone think of a way to unit test calls to OpenGL without wrapping the OpenGL API in a wrapper and using virtual calls? I don't want the performance penalty for looking up the functions in the vtable.
Are you sure the performance penalty is so bad that you need to avoid it? The time it takes to do a virtual-table lookup is probably insignificant compared to that of the actual operation.
I tried making a wrapper, inlining all the OpenGL calls, and using a template to call the API, but its really nasty.
My next idea is to replace the OpenGL namespace with my own mock functions.
I think I may have thought of another way. You could use #define to remove the "virtual" tag from the OpenGL wrapper. That way all the functions would be inlined and the compiler should make it just the same as calling the OpenGL functions directly. This works fine, because virtual functions are only needed for unit testing.
#pragma once #include "opengl.h" #if _DEBUG #define VIRTUAL_INLINE virtual #else #define VIRTUAL_INLINE inline #endif class OpenGLWrapper { public: VIRTUAL_INLINE() void glutInit(int* argc, char** argv) { ::glutInit(argc, argv); } };
Try using glTrace to see if the performance hit is too high. If not, using a wrapper should be fine. Otherwise, you could dynamically link to OpenGL, and use a (intercepting)wrapper just for the unit tests, then reset the wrapper to non-intercepting afterwards.
You can make the GNU linker redirect function calls. You could use that to redirect calls into a mock OpenGL library at link time, without changing your source code.
See also: TestFirstUserInterfaces, HowToTestCallsToStaticFunctions