Imagine that you have a method that requires an
InputStream, and you want to test that method. How can you test it?
In the Scala Cookbook I wrote how your Scala method can accept a Source instead of a File to make it easier to test, so I won’t write any more about that right now.
But if you have a method that accepts an
InputStream and you want to be able to test it with a
String, here’s what you can do:
// 1) create the desired String val html = MartinOderskyPage.content // 2) convert that String to an InputStream val testPageInputStream = new ByteArrayInputStream(html.getBytes)
The first line of code shown creates a
String object named
html. It does that by calling a
content method on a Scala object named
html object contains the same HTML content you’d get by downloading his Wikipedia page (or at least the same content you would have gotten when I downloaded it in 2014).
The second line of code does what you want, converting the
html String into a
ByteArrayInputStream, which is a type of
InputStream. It calls the
getBytes method on the String object, and uses that as a parameter to the
ByteArrayInputStream constructor. You can now pass the
testPageInputStream object to any method that requires an
If you needed to see how to convert a Scala (or Java)
String to an
InputStream, I hope this has been helpful.