gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 05:04:42 27 4
gpt4 key购买 nike

在我的类里面,我有两个版本的方法。一个需要一个 Exception ,另外一个String .

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

我如何转换 with(any(SubTypesException.class))JMockScalamock ?我可以想象使用谓词匹配( where ),这是要走的路吗?

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

要测试参数的运行时类型,您可以使用 ArgThat这是在 ScalaMock 中引入的 3.2.1连同辅助函数:
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])

关于scalamock:子类型上的通配符参数匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30162263/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com