【问题标题】:How to mock Java 8 Function in Spock Groovy如何在 Spock Groovy 中模拟 Java 8 函数
【发布时间】:2020-06-01 06:08:16
【问题描述】:

我想在 spock groovy 中模拟 Java 8 函数

下面是我的转换器界面

interface Transformer {
  String doSomething();
  Integer performTest();
  Function<List<Test>, String> findSuccess();
}

想在服务中模拟这个函数

transformer.findSuccess().apply(tests);  // service class code

请帮帮我

【问题讨论】:

  • 给它一个 lambda 怎么样?类似Transformer t = list -&gt; 'stubbed result'(如果您使用的是groovy 3)或Transformer t = {it.join('-test-')}
  • 以上不是FunctionaInterface,我现在更新了问题。

标签: java groovy lambda mocking spock


【解决方案1】:

我正在使用 groovy 2.5,并在我的测试用例中添加了以下内容。它正在工作

def function = {
  "1234"
} as Function<List<Test>, String>
1 * transformer.findSuccess() >> function

【讨论】:

  • 实际上,您的语法在我执行文本期间会产生运行时错误,但这有效:1 * transformer.findSuccess() &gt;&gt; (Function) { "1234" } 或者当然是def function = { "1234" },然后是1 * transformer.findSuccess() &gt;&gt; function
  • 在这种情况下您不需要as Function&lt;List&lt;Test&gt;, String&gt;,但是如果您希望它更安全,可以根据需要这样做。但后来我会使用Function&lt;List&lt;Test&gt;, String&gt; function = { "1234" }。或者你坚持我的版本,如果类型推断适合你,只需 def function = { "1234" }
猜你喜欢
  • 2021-11-26
  • 2020-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-31
  • 2020-05-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多