Ifdeffed Test Code

Years ago I started writing tests in the same file as the code they were testing, under ifdefs

     foo.c:

int bar() { return 22; }

#ifdef TEST int main() { assert( bar() == 22 ); } #endif //TEST

It is pleasant to colocate things like this.

However, it often created difficulties with makefiles, since you would have to keep the differently ifdeffed object files separate.

I now prefer not to do this.


Java supports this in a way that is more convenient.


So do Perl, Python and Ruby. Their mechanism is basically:

 if (the running program == this file name)
     run the tests

Then, to run the tests, simply invoke the module as if it were a program. You can do this for all modules except the main one.


It's evil because you need to create two libraries, one test, and one not. That's too much overhead.

You don't need to create two libraries -- just create one library with TEST not defined and a TestRunner that compiles and executes each of the modules.


> It's evil because you need to create two libraries, one test, and one not. That's too much overhead.

CsharpLanguage lets you have the best of both worlds by allowing you to include the tests right in the class body (just like java) and also to exclude them during a Release build, using #ifdefs. Having used JavaUnit for some time, I find C#'s way much more convenient.

-- KarlinFox


I'm confused. Are the things you're #ifdef'ing out assertions (in a DesignByContract sense) or UnitTests (in a TestFirst or at least xUnit sense)? Or are they something else entirely?


Assuming this is SelfTestPattern?, it is what MichaelFeathers's book WorkingEffectivelyWithLegacyCode calls InVivoTesting?. It's very easy to retrofit, and it's harmless in small doses.

But when featurizing, I (PhlIp) like to flip back and forth between the test and code files in an editor.
CategoryTesting

EditText of this page (last edited April 22, 2008) or FindPage with title or text search