简体   繁体   English

测试打印输出的函数

[英]Testing a function that prints outputs

I am trying to write a unit test for a function that prints some texts in C. I have tried everything possible but could not make it possible.我正在尝试为在 C 中打印一些文本的函数编写单元测试。我已经尝试了一切可能但无法实现。 I have seen similar questions, but mostly are written in C++.我见过类似的问题,但大多是用 C++ 编写的。 Suppose one of the functions I am trying to test is the following:假设我要测试的功能之一如下:

void verifyStudent(char string[10][40], int lines)
{
//some actions
printf("Is our Student");
//some other actions
printf("Not a student");
}

And the test as follows:测试如下:

void test_student()
{
//all initializations

char *exp_output = "Not a student";

//HOW CAN I VERIFY THAT WHAT'S PRINTED IS SAME AS THE exp-output?
}

You can do this, by wrapping your function and redirecting output to some stream other than stdout .您可以通过包装您的函数并将输出重定向到stdout以外的某个流来做到这一点。 I will slightly change the example, but the main idea is the same.我将稍微更改示例,但主要思想是相同的。 Suppose we have the following function:假设我们有以下函数:

void even(const int number)
{
    if(number % 2 == 0){
        printf("%d is an even number", number);
    } else{
        printf("%d is an odd number", number);
    }
}

Now we will change this to print into any stream and wrap it to keep normal performance for a user (even turn it into a static function, so the user of you library has no idea of the wrapping):现在我们将更改它以打印到任何流并包装它以保持用户的正常性能(甚至将其转换为静态函数,因此您库的用户不知道包装):

void _even(const int number, FILE* stream)
{
    if(number % 2 == 0){
        fprintf(stream, "%d is an even number", number);
    } else{
        fprintf(stream, "%d is an odd number", number);
    }
}

void even(const int number)
{
    _even(number, stdout);
}

To test _even , we can create a temporary file, redirect output of _even into it, and then check if it matches our prediction.为了测试_even ,我们可以创建一个临时文件,将_even输出重定向到其中,然后检查它是否与我们的预测匹配。

int test_even(const int input, const char* output)
{
    FILE* tmp = tmpfile();

    const int length = strlen(output) + 1;
    char buffer[length];

    _even(input, tmp); // Redirecting
    const int tmp_length = ftell(tmp) + 1; // how many characters are in tmp
    rewind(tmp);

    fgets(buffer, length, tmp); // Reading from tmp
    fclose(tmp);

    if(strcmp(buffer, output) == 0 && tmp_length == length){
        // Test succeded
        // Do what you want in here
    } else{
        // Test failed
    }
}

What exactly you should do when your test succeeds or fails is up to you, and up to how you design your unit testing.当您的测试成功或失败时,您究竟应该做什么取决于您,以及您如何设计单元测试。 And you can then run it like this:然后你可以像这样运行它:

test_even(17, "17 is an odd number");   // succeeds
test_even(0, "0 is an even number");    // succeeds
test_even(-1, "-1 is an even number");  // fails

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM