如何用C编写一个使用指针进行单元代码测试的方法



我在C中有以下单元测试代码。它不断返回错误Failed。在什么时候我会出错,或者单元测试代码有错误。单位代码如下:

#define TEST_LBSG   2494
#define TEST_LBS    5.5 
int testConvertLbsG(void)
{
double lbs = TEST_LBS;
int intA, intB, fail = 0;
printf("---------------------------n");
printf("Function: convertLbsGn");
printf("---------------------------n");
// Test-1: argument and return value
intA = intB = 0;
printf("Test-1: ");
intB = convertLbsG(&lbs, &intA);
if (intA == intB && intA == TEST_LBSG)
{
printf("<PASSED>n");
}
else
{
printf("<!!! FAILED !!!>n");
fail++;
}
// Test-2: return value only
intA = intB = 0;
printf("Test-2: ");
intA = convertLbsG(&lbs, NULL);
if (intA == TEST_LBSG)
{
printf("<PASSED>n");
}
else
{
printf("<!!! FAILED !!!>n");
fail++;
}
// Test-3: argument only
intA = intB = 0;
printf("Test-3: ");
convertLbsG(&lbs, &intA);
if (intA == TEST_LBSG)
{
printf("<PASSED>n");
}
else
{
printf("<!!! FAILED !!!>n");
fail++;
}
return fail;
}

我试图写的代码如下:

int convertLbsG(double* x, int* y) {
if (y == NULL)
{
return *x;
}
else
{
return *x = (*y);
}

}

哪里出错了

额外代码:

假设这是我的单元测试代码:

int testConvertLbs(void)
{
double lbs = TEST_LBS, dblA = 0.0;
int intB = 0, fail = 0;
printf("---------------------------n");
printf("Function: convertLbsn");
printf("---------------------------n");
printf("Test-1: ");
convertLbs(&lbs, &dblA, &intB);
if ((dblA == lbs / TEST_LBSKG) && (intB == TEST_LBSG))
{
printf("<PASSED>nn");
}
else
{
printf("<!!! FAILED !!!>nn");
fail++;
}
return fail;
}

下面是我的方法:

int convertLbs(double* x, double* y, int* z) {

}

在下面的代码中:

intA = intB = 0;
printf("Test-3: ");
convertLbsG(&lbs, &intA);
if (intA == TEST_LBSG)

仅更新lhs,而不更新intA。变量intA保持其旧值0,测试失败。

我想convertLbsG()的意图是更新第二个论点,而不是第一个。

int convertLbsG(double* x, int* y) {
if (y == NULL)
{
return *x;
}
else
{
return *y = (*x); // was *x = (*y);
}

此外,我建议添加const以避免将来出现类似问题。

int convertLbsG(const double* x, int* y)

最新更新