问题
I am practicing google test C. I have a bit of confusion when writing a test case for function_1
function.
typedef struct
{
int a; //4 byte
char b; //1 byte
char c; //1 byte
char d; //1 byte
char arr[3]; //3 byte
}ABCXYZ;
static void function_1(char *abc)
{
if (abc != null)
{
ABCXYZ *name =(ABCXYZ *)(abc + 4);
if (name->b == 1)
printf("ONE");
else if (name->b == 2)
printf("TWO");
else
printf("OTHER");
}
else
{
printf("INVALID");
}
}
I have written test case like this:
TEST(Test_function_1,abc_null)
{
function_1(null);
}
TEST(Test_function_1,one)
{
char arr[10]={1,0,0,0,0,0,0,0,0,0};
function_1(arr);
}
TEST(Test_function_1,two)
{
char arr[10]={2,0,0,0,0,0,0,0,0,0};
function_1(arr);
}
TEST(Test_function_1,other)
{
char arr[10]={3,0,0,0,0,0,0,0,0,0};
function_1(arr);
}
But when I check result and report coverage html, it is not cover all branchs in function. How I can change test case to cover entire branchs ?
回答1:
It's not about the test cases but your function has a problem.
This line of code ABCXYZ *name =(ABCXYZ *)(abc + 4);
does not help you to pass the value of the first element of the array into the field b
of struct name
.
So name->b
always has some random value and in these cases the value are happened to be different to 1
and 2
so you got the else
branch.
You need to allocate memory for name
and then assign value of abc[0]
to the field b
:
ABCXYZ *name = (ABCXYZ *) malloc (sizeof (ABCXYZ));
name->b = abc[0];
p/s: This function is wierd though.
来源:https://stackoverflow.com/questions/59509615/how-to-test-to-cover-all-branchs-of-function-casting-char-array-to-struct-use-go