Search code examples
scalastdin

How to override stdin to a String


Basic question, I want to set the standard input to be a specific string. Currently I am trying it with this:

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)))

Because that's similar to how I'd do it in Java, however str.getBytes seems to work differently in Scala as System in is set to a memory address when I check it with println....

I've looked at the Scala API: http://www.scala-lang.org/api/current/scala/Console$.html#setIn(in:java.io.InputStream):Unit and I've found

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

But this seems to only set the input stream for a specific chunk of code, I'd like this to be a feature in a Setup method in my JUnit tests.


Solution

  • My problem ended up being something related to my code, not this specific concept. The correct way to override Standard In / System In to a String in Scala is the following:

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

    My tests run correctly now.