Search code examples
scalatestingmockingmockitospecs2

Can I use a mock File in my Specs2 test for writing to a file? If so, How?


I've successfully used Specs2 to test serialization to a file, but the test uses a real file (written to /tmp/). I'd rather not touch disk just for a test. Is there a way to use a mocked file?

def serializeAndDeserializeFromDatafile[X <: CaseClass : Manifest](old: X, maybeGrater: Option[AvroGrater[X]] = None): X = {
val g = maybeGrater.getOrElse(grater[X])

//val outfile = mock[File]
val outfile = new File("/tmp/file1.avro")   

g.serializeToDataFile(outfile, old)  //Serialize to file

val infile = outfile
g.asObjectFromDataFile(infile)       //Deserialize from file 
}

I tried using Mockito to mock my outfile(the commented-out line above). In my naive attempt, I can create the Mock for File, hashCode: 1583021903, but it seems to be null when I try to serialize.

I think I'm missing a 'stub' of some sort, but I can't find any examples that are similar enough to suggest a solution. Any help would be appreciated.


Solution

  • I have a program (an autonomous written using Akka) that deals extensively in file system operations. I wrote it using ScalaIO (rather than native Java library java.io._ classes). ScalaIO includes, among other things, the RamFileSystem which allows you to mock file system contents and operations in ways that mirror real file system operations without involving file-system and I/O system calls.