无法在 spock 测试中捕获任何异常

时间:2021-07-02 15:42:12

标签: groovy spock

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

在我的班级

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

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

1 个答案:

答案 0 :(得分:1)

<块引用>

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

我无法重现那个。

请参阅位于 https://github.com/jeffbrown/red888/tree/351c1a24fa06216c59b858a43562c56cc1dcceb2test-question 分店。

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
相关问题