【问题标题】:Can Groovy/Spock mock both a method and the interface implementation at the same time in Kotlin?Groovy/Spock 可以在 Kotlin 中同时模拟方法和接口实现吗?
【发布时间】:2021-12-05 03:44:37
【问题描述】:

模拟类定义如下:

interface SomeInterface {
    val somethingCommon: String
}
class SomeClass(val somethingSpecific: String) : SomeInterface {
    override val somethingCommon: String
      get() = somethingSpecific
}

被测代码模拟 SomeClass 并在内部使用特定属性和公共接口。不幸的是,仅模拟特定属性不会模拟关联的接口方法,因此似乎有必要同时模拟两者:

def thing = Mock(SomeClass)
thing.somethingSpecific >> "blah"
thing.somethingCommon >> "blah"

在 Kotlin/Groovy/Spock 中有没有一种方法可以避免对这两种方法进行存根处理?我想出的最好办法是把一个与另一个存根,这可行,但很不幸:

def thing = Mock(SomeClass)
thing.somethingSpecific >> "blah"
thing.somethingCommon >> thing.somethingSpecific

【问题讨论】:

  • 你有你正在尝试的测试并抛出错误吗?在我的测试中,如果我打开SomeClass,那么当我只模拟thing.somethingCommon >> "blah"时它就可以工作了

标签: kotlin groovy mocking spock


【解决方案1】:

您描述的行为是 Spy,如果您没有 specified 任何返回值,Mock 将返回 null

Spock 只能模拟非最终类/方法,但您可以使用 https://github.com/joke/spock-mockable 动态打开它们进行测试。

【讨论】:

    猜你喜欢
    • 2019-08-29
    • 2020-05-23
    • 2013-09-29
    • 2013-01-12
    • 2017-07-11
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 2022-01-07
    相关资源
    最近更新 更多