2017-10-09 75 views
0

我有一個運行在終端之上的應用程序。Scala - ScalaTest:測試時模擬輸入

此應用程序只使用Scala和SBT,我正在使用ScalaTest進行測試。

我想測試所有組件,例如運行應用程序的集成測試,但爲此,我想模擬用戶通過標準輸入使用類似機器人的方式發送值。最重要的是,當我撥打readLinereadInt時,我想在測試時發送不同的值。

在此先感謝!


編輯1

所以,我這個代碼。它基本上打印用戶的選項。例如,我想要發送1,然後3,4,創建一個新的Cell並檢查我的CellArray,以檢查是否真的在該位置創建了一個新的單元。

do { 
    println("Select one of the options: \n \n"); 
    println("[1] Make a cell alive"); 
    println("[2] Next generation"); 
    println("[3] Halt"); 

    print("\n \n Option: "); 

    option = parseOption(readLine) 

}while(option == 0) 

option match { 
    case MAKE_CELL_ALIVE => makeCellAlive 
    case NEXT_GENERATION => nextGeneration 
    case HALT => halt 
} 
+0

基本上,你要做的就是對你的程序的邊緣(readLine/readInt)進行測試實現,它提供手動編碼或生成(例如ScalaCheck)值。在這裏放下一些你的代碼,我們可以嘗試幫助更多細節。 – Ren

回答

1

一般方法將沿着這些方向。

// This is the class containing the logic you want to test 
class MyInputThing { 
    def readInput() = readLine 

    def thingIWantToTest = { 
    val input = readInput 
    doStuffWithInput(input) 
    } 
} 

// This test class returns a value representing something you want to verify. 
class TestMyInputThing extends MyInputThing { 
    override def readInput = "123" 
} 

然後,在您的測試,使用TestMyInputThing.thingIWantToTest()和驗證的響應。你也可以把readInput放到一個trait中,參數化TestMyInputThing等的創建,以便清理它。我還建議尋求ScalaCheck,以便您不需要手動編寫測試場景。