Question

I have this piece of code

   for (element <- table.find;
     Right(info) = exceptionManager(mapper.getInfoFromDbObject(element)))
yield info

and I would like to unit test it. I want to mock table.find in order to return a sequence of element that I want. I have tried mocking hasNext() and next() methods of Iterator interface but it seems it is not working. Which is the method to mock a for comprehension?

Was it helpful?

Solution

Each for comprehension is translated to map, flatMap, filter method calls. So you should mock at least them.

You can find more information here (for example):

http://www.lambdascale.com/2010/12/the-adventures-of-a-java-developer-in-monadland/

And of course you will find deep explanation in Programming in Scala book.

Edit

But as Dave Griffith said, you can just initialize new Iterator yourself. Here is an example that uses Mockito and ScalaTest:

val table = mock[TableClass]
when(table find) thenReturn Iterator(new ModelObject(1), new ModelObject(2))

Edit 1

As Daniel noticed, filter method is now deprecated in for comprehensions. Instead you should use withFilter. For more information you can look in this thread:

http://scala-programming-language.1934581.n4.nabble.com/Rethinking-filter-td2009215.html#a2009218

and this related SO question:

guide to move from filter to withFilter?

OTHER TIPS

In theory, you should mock the "map" method, but you're probably better off simply having table.find return one of the predefined collection types.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top