c++ - 单元测试扫描

标签 c++ visual-studio unit-testing testing

(对不起我的英语)我正在尝试从 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/

相关文章:

c++ - 关于 VS 2010 中用于 C++ 的代码覆盖工具

c++ - 灰度图像中像素的质心

visual-studio - 安装扩展未检测到 Visual Studio 2017

javascript - 使用 Jest 测试一个应该抛出错误的函数,但总是收到 "function did not throw"错误

C++ 如何将此数组类型复制到 Vector

c++ - 将 struct 转换为 unsigned char *

c# - 使用 C# 和 Xamarin 防止按 F8(播放)按钮后启动 iTunes/Music.app

javascript - 我应该怎么做才能在 Visual Studio 中为我自己的 js 库获取 javascript 智能感知

javascript - 使用 Jasmine 2.0 对 $scope.$evalAsync 函数进行单元测试

java - 我应该在什么条件下测试 get() 和 set() 方法?