加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何在Scala中模拟一个功能参数的方法?

发布时间:2020-12-16 09:37:01 所属栏目:安全 来源:网络整理
导读:我试图模拟一个方法调用,它接受一个call-by-name参数: import org.scalatest.WordSpecimport org.scalatest.mock.MockitoSugarimport org.mockito.Mockito._import org.junit.runner.RunWithimport org.scalatest.junit.JUnitRunnertrait Collaborator { d
我试图模拟一个方法调用,它接受一个call-by-name参数:

import org.scalatest.WordSpec
import org.scalatest.mock.MockitoSugar
import org.mockito.Mockito._
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

trait Collaborator {
   def doSomething(t: => Thing)
}

trait Thing

@RunWith(classOf[JUnitRunner])
class Test extends WordSpec with MockitoSugar {
   "The subject under test" should {
      "call the collaborator" in {
         // setup
         val m = mock[Collaborator]
         val t = mock[Thing]

         // test code: this would actually be invoked by the SUT
         m.doSomething(t)

         // verify the call
         verify(m).doSomething(t)
      }
   }
}

我主要对Mockito感兴趣,因为我正在使用它,但是我有兴趣看看是否有任何一个主要的模拟框架能够进行这种测试。测试在运行时在验证行失败,出现错误

06001

如果我正确地理解情况,编译器会隐式地将t包装在一个返回t的空值函数中。然后,模拟框架将该函数与测试代码中生成的函数进行比较,这相当于但不等于()。

我的案例是一个比较简单的问题的版本,但我认为这将是任何高阶函数的问题。

解决方法

这看起来很丑陋,但希望能帮助你找到好的解决方案:

import org.scalatest.mock.MockitoSugar
import org.mockito.Mockito._

trait Collaborator {
   def doSomething(t: => Thing)
}

trait Thing

new MockitoSugar {
     // setup
     val m = mock[Collaborator]
     val t = mock[Thing]

     m.doSomething(t)

     classOf[Collaborator].getMethod("doSomething",classOf[Function0[_]]).invoke(
        verify(m),new Function0[Thing] { 
            def apply() = null
            override def equals(o: Any): Boolean = t == o.asInstanceOf[Function0[Thing]].apply() 
      })
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读