【发布时间】:2016-08-24 14:43:51
【问题描述】:
例如,我已经迷上了类型丰富
object MyImplicits{
implicit class RichInt(i: Int){
def complexCalculation: Int = i * 200
}
}
我在这样的代码中使用它
object Algorithm{
def apply(rand: Random) = {
import MyImplicits._
rand.nextInt.complexCalculation + 1
}
}
但是我现在如何隔离和单元测试算法呢?特别是,我想模拟complexCalculation 的实现,如下所示:
class MyAlgorithmTest extends FreeSpec with MockitoSugar{
import org.mockito.Mockito.when
"MyApgorithm" {
"Delegates complex calculation" in {
val mockRandom = mock[Random]
when(mockRandom.nextInt()).thenReturn(1)
// This wouldn't work, but is the kind of thing I'm looking for
//when(1.complexCalculation).thenReturn(2)
val expected = 1 * 2 + 1
val result = MyAlgorithm(mockRandom)
assert(result === expected)
}
}
}
【问题讨论】:
-
您的问题到底是什么?您是否要确保在测试期间将随机 int 对象转换为 RichInt 对象?还是您不知道如何将断言用于您不知道的随机值?
-
我相信@Pengin 想模拟
complexCalculation方法——但是因为RichInt对象的创建是隐式的,所以没有办法为此when指定RichInt子句对象。
标签: scala unit-testing dependency-injection mockito scalatest