当我模拟时,特定的对象方法正在执行实际的行为。预期的输出应该是10,因为我模拟了Calculate.add并将结果作为10返回
trait Base {
def add (parm1:Int, parm2:Int): Int
def fetc ():Any
def compute(): Any
}
object Calculate extends Base {
def add(parm1:Int, parm2:Int):Int = {
fetc()
compute
}
def fetc ():Any = {
// Making some api1 call
}
def compute ():Any = {
// Making some api2 call
}
}
object Engine {
def execute():any{
Calculate.add(10, 20)
}
}
Test
class TestEngine extends MockFactory {
it should "compute" in {
val res1:Int = 10
val calculate: Base = stub[Base]
val data = (calculate.add _).when(10, 20).returns(res1);
Engine.execute() // ExpectedOutput should be 10(res1),Since the I mocked the add method and returning the 10 value. Should not call the Calculate object fetch, compute behaviour.
}
}发布于 2019-12-03 17:46:43
尽管Calculate是模拟的& add方法已被存根,但add的实际功能仍将被执行,因为在Engine.execute方法中,Calculate对象引用用于访问add方法,Calculate本身也是一个对象,因此实际的代码将被执行。
object Engine {
def execute():any{
Calculate.add(10, 20)
}
}在Engine.execute中模拟计算的简单解决方案可以是使用传递了基变量的calculate对象作为方法参数。
object Engine {
def execute(base: Base): Int = {
base.add(10, 20)
}
}
class TestEngine extends MockFactory {
it should "compute" in {
val res1: Int = 10
val calculate: Base = stub[Base]
val data = (calculate.add _).when(10, 20).returns(res1);
//mocked_calculate
Engine.execute(mocked_calculate)
}
}https://stackoverflow.com/questions/59153773
复制相似问题