【问题标题】:How do I write a unit-test to throw an exception from the Mock method of Operation return type?如何编写单元测试以从 Operation 返回类型的 Mock 方法中抛出异常?
【发布时间】:2019-12-09 16:03:48
【问题描述】:

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

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

有A类,B类

// class A

private ClassB b;

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

methodP() 的返回类型是 Promise&lt;&gt; methodO() 的返回类型为Operation

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

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

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

// 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'

【问题讨论】:

    标签: exception mocking spock operation ratpack


    【解决方案1】:

    改变这一行:

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

    开:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-19
      • 2018-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多