2016-11-04 112 views
0

(對不起,我的英語)我想從C++的代碼進行單元測試。在下一個函數(菜單)中,沒有任何參數放入()中。但是,這個功能有一個scanf,我想測試,但我不知道如何做到這一點。單元測試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); 
} 
+0

你能修改現有的代碼嗎?然後你應該將menu()分成兩個函數,一個顯示菜單並讀取輸入,另一個作用於輸入,這將很容易測試。 – Rene

+0

如果不是,並且您在* UX上:將輸入參數寫入文本文件,運行帶有輸入重定向到文本文件的測試程序,然後調用menu()並測試結果。您也可以在同一個文件中有多個輸入值,然後多次調用menu()。 (當然會有其他更復雜的解決方案,使用fdup) – Rene

回答

1

如果您使用C++函數cin和cout可以重定向緩衝區。

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; 
} 
+0

'C/C++'不是一種語言。 –

+0

好吧,它當然不是。我以爲我在問題中看到了這一點,但我錯了。 – MacUseless

+0

它確實說C++,所以我仍然在明確:) – MacUseless