在Scala中理解模拟 [英] Mock for comprehension in scala
问题描述
我有这段代码
for (element <- table.find;
Right(info) = exceptionManager(mapper.getInfoFromDbObject(element)))
yield info
,我想对其进行单元测试.我想模拟table.find以返回我想要的元素序列.我曾尝试模拟Iterator接口的hasNext()
和next()
方法,但似乎无法正常工作.哪种方法可以模拟a进行理解?
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?
推荐答案
用于理解的内容均转换为map
,flatMap
,filter
方法调用.因此,您至少应该嘲笑它们.
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/
当然,您会在在Scala书中编程中找到深入的解释.
And of course you will find deep explanation in Programming in Scala book.
但是正如 Dave Griffith 所说,您可以自己初始化新的Iterator
.这是一个使用 Mockito 和 ScalaTest :
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))
编辑1
正如 Daniel 所注意到的,出于理解的考虑,现在不推荐使用filter
方法.相反,您应该使用withFilter
.有关更多信息,请参见此线程:
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
和这个相关的SO问题:
and this related SO question:
这篇关于在Scala中理解模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!