2016-11-07 73 views
0

基本問題,我想將標準輸入設置爲特定的字符串。目前我這個嘗試它:如何將stdin覆蓋爲字符串

import java.nio.charset.StandardCharsets 
import java.io.ByteArrayInputStream 
// Let's say we are inside a method now 
val str = "textinputgoeshere" 
System.setIn(new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8))) 

因爲這是類似我怎麼會做它在Java中,但str.getBytes似乎被設置爲一個內存地址時,我檢查,在斯卡拉不同的方式工作的系統它的println ....

我已經看過了Scala的API:http://www.scala-lang.org/api/current/scala/Console $#的.html非瑟酮(在:java.io.InputStream中):單位 我發現

def withIn[T](in: InputStream)(thunk: ⇒ T): T 

但是,這似乎只是爲特定的代碼塊設置輸入流,我想這是我的JUnit測試中的Setup方法中的一項功能。

+0

Scala對副作用有輕微的不喜歡,而且這是一個相當殘酷的問題 - 您是否也可以將輸入流傳遞到您正在測試的方法中? – Reactormonk

+0

看起來像重複:http://stackoverflow.com/questions/40344117/create-user-prompt-and-simulate-interaction/40350178 – tkachuko

回答

1

我的問題最終成爲與我的代碼相關的東西,而不是這個特定的概念。覆蓋標準在/系統在給Scala中的一個字符串的正確方法如下:

val str = "your string here" 
val in: InputStream = new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8)) 
Console.withIn(in)(yourMethod())" 

我現在測試正常運行。

+0

此外這個主題是覆蓋 在[官方scala.Console文檔](http:///www.scala-lang.org/api/current/scala/Console$.html) 可以使用 java.io.StringReader作爲輸入源 'val input = new StringReader(s「$ {customStrInput} \ n 「)' 或文件內容 'val input:Reader = openFile(」file.txt「)' for'Console.withIn(input){...} –