Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unit tests for C++ criterion

I’m trying to make unit tests with criterion for my C++ code but I can’t figure out how to test a function that only print and do not return anything. Here’s what I tried:

//the function to test

#include <iostream>
#include <fstream>

void my_cat(int ac, char **av)
{
    if (ac <= 1)
        std::cout << "my_cat: Usage: ./my_cat file [...]" << std::endl;
    for (unsigned i = 1; i < ac; i += 1) {
        std::ifstream file (av[i]);
        if (file.fail()) {
            std::cout << "my_cat: ";
            std::cout << av[i];
            std::cout << ": No such file or directory" << std::endl;
        }
        else if (file.is_open()) {
            std::cout << file.rdbuf() << std::endl;
        }
        file.close();
    }
}
//the test
#include  <criterion/criterion.h>
#include  <criterion/redirect.h>

void my_cat(int ac, char **av);

Test(mycat, my_cat)
{
    char *av[] = {"./my_cat", "text.txt"};
    my_cat(2, av);
}

But now that I’m here I don’t know what to use to check if the print is correct.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

With gtest, I think this can help you

testing::internal::CaptureStdout();
std::cout << "My test";
std::string output = testing::internal::GetCapturedStdout();

refer from : How to capture stdout/stderr with googletest?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading