Unit Test Scanf

Unit Test Scanf

(Sorry for my english) I'm trying to make a unit test from a code of c++. In the next function (menu) there aren't any parameter into (). But into this funciton there are a scanf,that i would like testing but I haven't any idea how to make it.

Can I test scanf from Unit Test?

Thank you.

Code from function:

void principal::menu()
{
    int choice;
    system("cls");
    printf("\n--------MENU--------");
    printf("\n1 : Jugador X");
    printf("\n2 : Jugador O");
    printf("\n3 : Sortir");
    printf("\nTria el tipus de jugador: ");
    scanf_s("%d", &choice);
    turn = 1;
    switch (choice)
    {
    case 1:
        player = 1;
        comp = 0;
        player_first();
        break;
    case 2:
        player = 0;
        comp = 1;
        start_game();
        break;
    case 3:
        exit(1);
    default:
        menu();
    }
}

Code from test:

...
TEST_METHOD(menu){
   principal p; //this is the class --> not matter now

   //test code
}

If the code have a parameter I use the next code:

 ...
 TEST_METHOD(menu){
   principal p; //this is the class --> not matter now

   //test code
   Assert::AreEqual(result, parameter to enter);
}
2

1 Answer

If you use the C++ functions cin and cout you can redirect the buffer.

E.g.

#include <iostream>
#include <sstream>
#include <random>
#include <ctime>

int main()
{
    auto cout_buf = std::cout.rdbuf();
    std::stringbuf sb;
    std::cin.rdbuf(&sb);
    std::cout.rdbuf(&sb);

    std::mt19937 rand(time(nullptr));
    std::cout << (rand() % 100);

    int number;
    std::cin >> number;

    std::cout.rdbuf(cout_buf);
    std::cout << "The number was " << number << std::endl;

    return 0;
}
6

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor
Author

Sophia Al-Mansoor

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.