1

我想编写一个单元测试来从 Operation 返回类型的 Mock 方法中抛出异常。

我正在用 Groovy 中的 Spock 编写单元测试。

有A类,B类

// class A

private ClassB b;

Promise<String> foo() {
    return b.methodX()
        .nextOp(s -> {
            return b.methodY();
        });
}

返回类型为methodP()isPromise<> 返回类型methodO()Operation

// class B
public Promise<String> methodP() {
    return Promise.value("abc");
}

public Operation methodO() {
    return Operation.noop();
}

单元测试中 A 类模拟 ClassB 的 foo() 方法的单元测试

// Spock unit-test

ClassA a = new ClassA()
ClassB b = Mock()

def 'unit test'() {
    given:

    when:
    execHarness.yield {
        a.foo()
    }.valueOrThrow

    then:
    1 * b.methodP() >> Promise.value("some-string")
    1 * b.methodO() >> new Exception("my-exception")

    Exception e = thrown(Exception)
    e.getMessage() == "my-exception"
}

我预计会抛出异常,但抛出 GroovyCaseException 并且测试失败。

错误信息说,

org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'java.lang.Exception: my-exception' with class 'java.lang.Exception' to class 'ratpack.exec.Operation'
4

1 回答 1

3

更改此行:

1 * b.methodO() >> new Exception("my-exception")

上:

1 * b.methodO() >> { throw new Exception("my-exception") }

因为methodO()预计不会返回 Exception实例(如您的示例),但预计会被抛出(通过使用闭包)。

于 2019-08-01T06:37:09.700 回答