问题
I have to test several routines/functions that have several if statements that leads to a terminate() or exit() statement that stops the test execution.
I was wondering what's the best/correct approach in testing functions like this?
For example, if I had something like the following:
void function foo(void)
{
if(conditionA)
{
Terminate( //include infinite while loop resulting in timeout);
}
if(conditionB)
{
Terminate( //includes infinite white loop resulting in timeout);
}
}
How do I hit conditionB when I have a test case that is true for conditionA?
I think I would have to create a separate test case for conditionB to be true (and condition A to be false). However, the test still executes conditionA because I have two test cases run. Test Case #1, will enter conditionA and exit the test. Withby Test Case #2, will not run because of Test Case #1.
So, how should I structure the flow of my testing paradigm?
Currently, I have a test suite for each function that contains several test cases.
回答1:
Using exit
outside of main
is usually a bad idea; callers are offered little opportunity to clean up any resources sanely prior to the process terminating.
Think about it... What happens when fopen
fails? What about fgets
, malloc
, pthread_create
, socket
? Do any of those call exit
? Don't you think it'd be sensible to design your failure modes to be as consistent as possible with the rest of the world?
Use a return value and let the caller decide whether to terminate or not... Then you can construct separate testcases for each function and... viola! Your problem has disappeared...
回答2:
You have 2 options:
1 Run the test in separate processes - a framework like check can do that easily for you.
Check is a unit testing framework for C. It features a simple interface for defining unit tests, putting little in the way of the developer. Tests are run in a separate address space, so both assertion failures and code errors that cause segmentation faults or other signals can be caught
2 Stub the offending function - either by linking your own version of terminate() function or by using a macro to redefine terminate to your own version. i.e.#define terminate(_dummy_) my_terminate(_dummy_)
回答3:
Simple:
void function foo(void)
{
if(conditionA)
{
if(conditionB)
exit(0);
}
else if(conditionB)
{
exit(0);
}
}
来源:https://stackoverflow.com/questions/32131027/testing-conditions-that-exit-the-test