开发者

How to best turn on/off unit tests using #defines

I have a file with unit tests

    testOne() {...}
    testTwo() {...}
...

but when I am troubleshooting I would like to turn off all except the unit test that is causing problems (due to massive amount of logging). 开发者_如何学GoAt the moment I have done like this:

#if 0
testOne() {...}
#endif
..
#if 1
testTroublesome() {...}
#endif

But I was wondering if there is some better more convenient way to do this?


You could for example have an environment variable to signify which test to run, with unset meaning run them all (which would be the usual case). Like so: (this is C, but I think it'll work in objetive C as well)

char *env = getenv ("MY_TEST_ENV");

and then when running each test

if (! env || 0 == strcmp (env, "testOne"))
  testOne();

Or you could put the same condition inside the test itself and just return if it fails. This wouldn't keep your tests from being compiled though, but I don't think that's your problem is it? Just set the environment variable to the test you want to run, and none of the others will.

EDIT
To make it even easier, put that in a macro

#define RUN_TEST(fn) do{if(!getenv("MY_TEST_ENV")||!strcmp(getenv("MY_TEST_ENV"),#x))x();}while(0)

and always execute your test with that

RUN_TEST(test_one);

... and you've got yourself a little unit test framework going. Before taking it too far and reinventing too many wheels though, you should (as has been pointed out) perhaps take a look at existing frameworks.


Two notes:

  • most unit test frameworks offer the possibility to organize your tests into suites, thus you can run only specific tests.
  • you should consider reconfiguring logging in unit tests so that no logs are produced. Unit test output should be the simplest possible, to avoid drowning your focus into useless details. I.e. if all tests pass, the only output you should see is something like "123 tests passed." or if there are errors, the names of the failing test(s) and the relevant error messages.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜