12.6. Pretending that a String Is a File
Problem
Typically for the purposes of testing, you want to pretend that a
String is a file.
Solution
Because Scala.fromFile and
Scala.fromString both extend scala.io.Source, they are easily
interchangeable. As long as your method takes a Source reference, you can pass it the BufferedSource you get from calling Source.fromFile, or the Source you get from calling Source.fromString.
For example, the following method takes a Source object and prints the lines it
contains:
importio.SourcedefprintLines(source:Source){for(line<-source.getLines){println(line)}}
It can be called when the source is constructed from a String:
vals=Source.fromString("foo\nbar\n")printLines(s)
It can also be called when the source is a file:
valf=Source.fromFile("/Users/Al/.bash_profile")printLines(f)
Discussion
When writing unit tests, you might have a method like this that you’d like to test:
packagefooobjectFileUtils{defgetLinesUppercased(source:io.Source):List[String]={(for(line<-source.getLines)yieldline.toUpperCase).toList}}
As shown in the following ScalaTest tests, you can test the
getLinesUppercased method by passing
it either a Source from a file or a
String:
packagefooimportorg.scalatest.{FunSuite,BeforeAndAfter}importscala.io.SourceclassFileUtilTestsextendsFunSuitewithBeforeAndAfter{varsource:Source=_after{source.close}// assumes the file has the string "foo" as its first linetest("1 - foo file"){source
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access