gpt4 book ai didi

c++ - 单元测试扫描

转载 作者:行者123 更新时间:2023-11-28 05:26:43 25 4
gpt4 key购买 nike

(对不起我的英语)我正在尝试从 C++ 代码进行单元测试。在下一个功能(菜单)中, () 中没有任何参数。但是在这个函数中有一个 scanf,我想测试一下,但我不知道如何制作它。

我可以从单元测试中测试 scanf 吗?

谢谢。

函数代码:

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

关于c++ - 单元测试扫描,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40422303/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com