【问题标题】:Can't catch any exceptions in spock tests [closed]在 spock 测试中无法捕获任何异常[关闭]
【发布时间】:2021-07-02 15:42:12
【问题描述】:

即使是最简单的情况,我也无法让它工作。

在我的课堂上

public static String fail(somestring) {
    throw new RuntimeException()
}

这是我的测试:

@Test
public void "Throws exception"() throws Exception {
  given:
    MyClass test = new MyClass()
  when:
    test.fail("sdlkfjlsdkfj")
  then:
  thrown(RuntimeException)
  // also tried this
  //throw new RuntimeException()
}

我的它只是抛出一个接受并且测试失败。似乎 throw 被忽略了。

【问题讨论】:

  • 我认为您混淆了 JUnit 和 Spock。您使用的注释来自 JUnit。您另一个问题中的基类来自 Jenkins,它使用 JUnit。只需在 groovy(甚至 Java AFAIR)中添加when: 或类似的东西,就只是生成一个标签并且是有效代码——如果你不打算“转到”它,那就是无操作。所以这基本上是stackoverflow.com/questions/25519736/… 的复制品,带有额外的误导层。

标签: groovy spock


【解决方案1】:

我的它只是抛出一个接受并且测试失败。

我无法重现。

查看test-question 分支https://github.com/jeffbrown/red888/tree/351c1a24fa06216c59b858a43562c56cc1dcceb2

app/src/main/groovy/red888/MyClass.groovy

package red888

class MyClass {

    // unclear why this is static in the question, but
    // left static here for consistency
    public static String fail(somestring) {
        throw new RuntimeException()
    }

}

app/src/test/groovy/red888/MyClassTest.groovy

package red888

import spock.lang.Specification

class MyClassTest extends Specification {
    public void "Throws exception"() throws Exception {
        given:
        MyClass test = new MyClass()
        when:
        test.fail("sdlkfjlsdkfj")
        then:
        thrown(RuntimeException)
    }
}

测试通过了。

~ $ mkdir demo
~ $ cd demo

demo $ git clone git@github.com:jeffbrown/red888.git
Cloning into 'red888'...
(...)

demo $ cd red888
red888 (main)$ git checkout test-question
Branch 'test-question' set up to track remote branch 'test-question' from 'origin'.
Switched to a new branch 'test-question'

red888 (test-question)$ cat app/src/test/groovy/red888/MyClassTest.groovy 
(...)
class MyClassTest extends Specification {
    public void "Throws exception"() throws Exception {
(...)

red888 (test-question)$ ./gradlew test
BUILD SUCCESSFUL in 4s
3 actionable tasks: 3 executed

【讨论】:

    猜你喜欢
    • 2011-06-30
    • 1970-01-01
    • 2019-10-30
    • 2021-01-21
    • 1970-01-01
    • 2014-05-10
    • 1970-01-01
    • 1970-01-01
    • 2012-12-22
    相关资源
    最近更新 更多