首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何参数化Java方法和类

如何参数化Java方法和类
EN

Stack Overflow用户
提问于 2021-11-26 20:06:20
回答 1查看 46关注 0票数 0

我正在使用Spock进行单元测试。我想要动态测试Java方法和类,如下面的示例所示。Audit是一个Java类。此外,如果可能的话,我还想让Audit类成为一个参数

代码语言:javascript
复制
given:
     Audit audit = GroovyMock()
     expression
     BatchAudit bean = new BatchAudit()

when:
    bean.insertAudit(audit)
then:
    thrown(exc)
where:
    expression | exc
    audit.getFileName() >> {throw new SQLException(new Throwable())} | DataAccessException
EN

回答 1

Stack Overflow用户

发布于 2021-11-27 10:47:10

只需进行一些修改即可实现:

对于闭包,您需要将其设置为闭包(由于AST中的一些怪癖,闭包不能是数据表中的第一个元素,因此它必须与expectedException)

  • you互换位置对于闭包,需要使用expression.rehydrate(null, this, this)

传递给闭包

代码语言:javascript
复制
import spock.lang.*

class Audit {
  String getFileName() {
    "foo"
  }
}

class BatchAudit {
  void insertAudit(Audit a) {
    println a.getFileName()
  }
}

class ASpec extends Specification {
  def "test"() {
    given:
    Audit audit = Mock()
    // we need to rehydrate the closure, so that `this` and are correct
    expression.rehydrate(null, this, this).call(audit)
    BatchAudit bean = new BatchAudit()

    when:
    bean.insertAudit(audit)
      
    then:
    Exception e = thrown()
    expectedException.isInstance(e)
      
    where:
    expectedException     | expression
    IllegalStateException | { it.getFileName() >> { throw new IllegalStateException() } }
  }
}

Groovy Webconsole中尝试一下。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70129549

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档