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

scalamock:子类型上的通配符参数匹配

发布时间:2020-12-16 08:44:25 所属栏目:安全 来源:网络整理
导读:在我的班上,我有两个版本的方法.一个是异常,另一个是字符串. class Foo { def method(e: Exception) = ??? def method(s: String) = ???} 在JMock中,我可以基于其类型模拟对方法的调用.请注意,我正在使用Exception的子类型来具体了解我在测试中所期望的内容.
在我的班上,我有两个版本的方法.一个是异常,另一个是字符串.

class Foo {
  def method(e: Exception) = ???
  def method(s: String) = ???
}

在JMock中,我可以基于其类型模拟对方法的调用.请注意,我正在使用Exception的子类型来具体了解我在测试中所期望的内容.

context.checking(new Expectations() {{              
    oneOf(mock).method(with(any(SubTypedException.class)));
}}

在Scalamock中,我可以使用通配符来匹配

(mock.method(_: Exception)).expects(*).once

当我尝试匹配特定的子类型时,以下内容无法编译(我意识到这在Scala中没有意义).

// doesn't compile    
(mock.method(_: SubTypedException)).expects(*).once

如何将JMock中的with(any(SubTypesException.class))转换为Scalamock?我可以想象使用谓词匹配(在哪里),这是要走的路吗?

Edit: Thinking about it,the JMock with(any(SubTypedException)) is more about keeping the compiler happy and expressing intent. As I understand it,the Matcher is an IsAnything matcher so won’t actually fail a test if a different type of exception is thrown.

So,it may be asking a bit much of Scalamock to both capture the intent and fail the test under the right circumstance. Bonus points in explaining how to do something like instanceOf in Scalamock.

解决方法

首先:以下内容无法编译,因为类型归属仅用于帮助(静态)重载分辨率.该行没有Scalamock特有的内容:

(mock.method(_: SubTypedException))

要测试参数的运行时类型,可以使用ScalaMock 3.2.1中引入的ArgThat以及辅助函数:

import scala.reflect.ClassTag

def typedArg[T,U : ClassTag]: ArgThat[T] = new ArgThat[T]({
  case x: U => true
  case _ => false
})

(mock.method(_: Exception)).expects(typedArg[Exception,SubTypedException])

(编辑:李大同)

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

    推荐文章
      热点阅读