【问题标题】:Scala mocking the behaviourScala嘲笑这种行为
【发布时间】:2020-03-27 22:37:30
【问题描述】:

当我模拟特定对象方法时,它正在执行实际行为。 预期的输出应该是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.

    }
}

【问题讨论】:

    标签: scala unit-testing mockito powermockito stub


    【解决方案1】:

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

    object Engine {
      def execute():any{
        Calculate.add(10, 20)
      }
    }
    

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

    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) 
      }
    }
    

    【讨论】:

    • 这是一种依赖注入的概念吧?将依赖模块作为参数传递。除此之外,我们是否有任何测试库来伪造函数行为?
    • 是的,将依赖模块作为参数传递。可能还有其他可用的选项,但我不知道它们,传递依赖项也是最可靠和可扩展的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-27
    • 2016-10-02
    • 2019-12-20
    • 1970-01-01
    • 2019-02-15
    相关资源
    最近更新 更多