单元测试扫描



(对不起我的英语)我正试图从c++代码进行单元测试。在下一个函数(菜单)中,()中没有任何参数。但是在这个函数中有一个扫描器,我想测试一下,但是我不知道怎么做。

我可以从单元测试中测试扫描吗?

谢谢。

函数代码:

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();
    }
}

代码来自test:

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

如果代码有参数,我使用下一个代码:

 ...
 TEST_METHOD(menu){
   principal p; //this is the class --> not matter now
   //test code
   Assert::AreEqual(result, parameter to enter);
}

如果你使用c++函数cin和cout,你可以重定向缓冲区。

#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;
}

最新更新