Mock for comprehension in scala

ε祈祈猫儿з 提交于 2019-12-25 02:22:26

问题


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?


回答1:


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?




回答2:


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.



来源:https://stackoverflow.com/questions/5128229/mock-for-comprehension-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!