我正在尝试测试以下功能
class someClass {
def someMethod() = {
val x = someObject.someOtherMethod()
//some logic that i want to test
}
}
有没有办法模拟val x或someOtherMethod调用而不传递x
答案 0 :(得分:0)
如果SomeObject真的是Object
,我不相信它有一些反射黑魔法。
一种常见的模式是具有定义对象的公共方法的特征,并使对象扩展特征。
现在SomeClass
可能取决于SomeObject
特征:例如
trait SomeObject {
def someMethod: Unit
}
object SomeObject extends SomeObject {
def someMethod = println("real method called")
}
class SomeClass(someObject: SomeObject)
并且在测试中你可以模拟这个特性:
val mockObject = mock[SomeObject]
when(mockObject.someMethod).thenReturn(())
val someClass = new SomeClass(mock[SomeObject])
编辑:一些Unsafe
魔法。
import sun.misc.Unsafe
object Foo {
val length: String => Int = {s => s.length}
}
Foo.length("foo") // 3
val unsafe = {
val f = classOf[Unsafe].getDeclaredField("theUnsafe")
f.setAccessible(true)
f.get(null).asInstanceOf[Unsafe]
}
val offset = unsafe.objectFieldOffset(Foo.getClass.getDeclaredField("length"))
val doubleLength: String => Int = { s=> s.length * 2}
unsafe.putObject(Foo, offset, doubleLength)
Foo.foo("foo") // 6
不幸的是,当Foo.length
是def
而不是val