首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >模拟行为的Scala

模拟行为的Scala
EN

Stack Overflow用户
提问于 2019-12-03 17:21:17
回答 1查看 90关注 0票数 1

当我模拟时,特定的对象方法正在执行实际的行为。预期的输出应该是10,因为我模拟了Calculate.add并将结果作为10返回

代码语言:javascript
复制
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.

    }
}
EN

回答 1

Stack Overflow用户

发布于 2019-12-03 17:46:43

尽管Calculate是模拟的& add方法已被存根,但add的实际功能仍将被执行,因为在Engine.execute方法中,Calculate对象引用用于访问add方法,Calculate本身也是一个对象,因此实际的代码将被执行。

代码语言:javascript
复制
object Engine {
  def execute():any{
    Calculate.add(10, 20)
  }
}

在Engine.execute中模拟计算的简单解决方案可以是使用传递了基变量的calculate对象作为方法参数。

代码语言:javascript
复制
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) 
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59153773

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档