Reputation: 1455
I'm doing unit tests. I have to test ALL possible if..else
cases. But in this if
statement:
int32_t i32Res = snprintf(buffer, len, "The%d_String_%d", 0, u8Idx);
if ((i32Res < 0) || (i32Res >= len))
{
return enuErrVal;
}
i32Res
is never < 0
, it always ends up having the string's size value. I can only force the buffer
and len
variables. I have tried with a null buffer
but it crashes before actually reaching the if
. I have tried with very small and very big sizes in buffer
. I tried with low (2
) values on len
.
I know snprintf()
returns -1
on encoding errors, how can I force this?
Upvotes: 2
Views: 349
Reputation: 6019
This is a clash between a requirement which is unreasonable - 100% code coverage in unit tests - and actual real-life programming languages and libraries (or APIs). Best bet is to rewrite the code so that the <0
test is separate from the >len
test, then mark the <0
test as fatal/never happens in the code with, e.g., a call to abort()
, and then finally write up a request for an exception to the 100% rule you're suffering with.
int32_t i32Res = snprintf(buffer, len, "The%d_String_%d", 0, u8Idx);
if (i32Res < 0)
{
abort();
}
if (i32Res >= len)
{
return enuErrVal;
}
Upvotes: 0
Reputation: 54345
Probably the best way to get test coverage for code like this is to use an interposer library. This is a shared library that goes between your code and the system C library. Some of them have function calls for testing which can command it to do things like return NULL for the next malloc call.
There's this closed question which still has some good info it seems: Unit Testing C Code
You'll have to search around to find a good testing library layer. I've used one, but it was 15 years ago and I don't quite remember what its name was.
Upvotes: 1
Reputation: 333
From https://support.sas.com/documentation/onlinedoc/sasc/doc700/html/lr1/z2056522.htm#z2056525:
The snprintf function returns an integer value that equals, in magnitude, the number of characters written to the area addressed by dest. If the value returned is negative, then either the maxlen character limit was reached or some other error, such as an invalid format specification, has occurred. The one exception to this is if an error occurs before any characters are stored, snprintf returns INT_MIN (-2**31) .
Upvotes: 1