c - 测试静态变量

标签 c validation unit-testing testing verification

我正在尝试对使用静态 32 位无符号整数的函数进行单元测试。

被测函数会将无符号整数递增 1。

所以,它本质上是:

void IncrementCount() {
    Spi_count++;
}

Spi_Count 变量通过将输入作为最大值进行测试时,即 0xFFFFFFFF 然后,如果我期望 0x100000000 作为输出,则测试通过。如果我期望 0 作为输出,那么它也会通过。

无符号变量如何通过值 0 和 0x100000000 的测试?

最佳答案

0x100000000 不是 32 位数字。 32 位是 4 个字节,或 8 个十六进制数字。您正在尝试检查 5 个字节 (0x1 00 00 00 00),而不是 4 个。如果没有您的代码,则无法确定,但编译器可能在比较中使用较低的 4 个字节,其计算结果为 0,因此你的测试工作。

Simple coding example to reproduce the problem .

#include <stdio.h>

int main(void) {
    // your code goes here
    unsigned int cX=-1;

    printf("%04X\n", cX);
    cX++;
    printf("%04X\n", cX);

    // Doing an explicit test of the unsigned int to 0x100000000 evaluates to false, as expected
    printf("%d\n", cX==0x1000000);                 // Outputs 0 (false)

    // If you cast the right side down to an unsigned int, then the high order bytes are lost
    // and you are essentially comparing against 0, so the comparison is a success
    printf("%d\n", cX==(unsigned)0x100000000);     // Outputs 1 (true)


    // You can do the same thing by accident using a hidden cast by calling a function.  Both
    // parameters are cast down to unsigned ints for the call so the right hand side loses its
    // most significant bytes, resulting in 0 again.
    printf("%d\n", compare(cX, 0x100000000));     // Outputs 1 (true)


    return 0;
}

int compare(unsigned x, unsigned y) {
    return x==y;
}

关于c - 测试静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27449589/

相关文章:

c++ - 插入C结构函数指针

c++ - 了解 C 和 C++ 中的暂定定义

security - TDD 能否成为过度杀伤数据验证的有效替代方案?

php - Visual Studio Code PHP 验证错误 : Cannot validate since/usr/bin/php is not a valid php executable

php - 让 DI 容器替换全局 $registry 对象是一种好习惯吗?

c - 从数组中输入几个数字,每个数字检查是否为整数

在 O(log n) 中计算 x ^ y

javascript - Angular 将输入类型 ="email"验证为类型 ="text"

javascript - Sinon.JS 的 stub.callsArg(index) 是做什么的?

java - 在单元测试中我应该进行多少对象初始化?