How To Test Calls To Static Functions

How do you test the following C code?

  char* write(char* str)
  {
     int handle = device_open();
     if (handle != 0)
     {
       device_write(handle, str);
       device_close(handle);
       return "";
     }
     else
     {
       return "Unable to open device";
     }
  }


Solution: Put a wrapper around the static calls.

Using C++ it would be easy test by using wrapping the device_* calls into a class, and passing a mock object to the write function. Is this why "object oriented" languages are better?

Drawbacks: Using virtual functions is a bit slower. For anything that is doing I/O, the cost of a virtual function call is insignificant.


Solution: Use Aspect Oriented Programming if you can figure it out

Using Java (Aspect/J) or Ruby I think you could redirect the static functions to mock functions and test that way.

Drawbacks: Involves new technology I don't know how to use.


Solution: Include mock versions of the functions in an include file

One solution might be to write some mock device_* functions and put them in another include file. When you test you use the special include file, but you use the real include file in production.


Solution: Swap in mock functions at link time (StaticPolymorphism)

The simple solution is to swap in the mock functions at link time. This works in Java, Ruby and, yes, even C. In languages and environments with dynamic linking it's trivial to do by adding the directory containing mock implementations to the front of the search path when running in test cases. There's no need to jump onto a faddish bandwagon like AOP. Existing tools already do all you need.


Solution: Use the real calls

An even simpler solution is to use the real device. Yes, you'll be testing more than just this method, but you'll find out of the device works as well.

My device costs $45,000 so I'm not allowed to use it during development.

Expensive devices never fail, so there's no point in testing with them. :-)

Drawbacks:


See also HowToUnitTestOpenGlCalls


EditText of this page (last edited March 1, 2004) or FindPage with title or text search