简体   繁体   English

如何编写单元测试以从Operation返回类型的Mock方法引发异常?

[英]How do I write a unit-test to throw an exception from the Mock method of Operation return type?

I would like to write a unit-test to throw an exception from the Mock method of Operation return type. 我想编写一个单元测试,以从Operation返回类型的Mock方法引发异常。

I'm writing the unit-test with Spock in Groovy. 我正在Groovy中用Spock编写单元测试。

There are class A, and B 有A类和B类

// class A

private ClassB b;

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

Return type of methodP() is Promise<> Return type of methodO() is Operation methodP()返回类型为Promise<> methodO()返回类型为Operation

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

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

Unit-test for foo() method of Class A Mocking ClassB in the unit-test 单元测试中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"
}

I expected the Exception is thrown, but GroovyCaseException was thrown and test failed. 我预计会引发异常,但会引发GroovyCaseException且测试失败。

Error message says, 错误消息说,

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

Change this line: 更改此行:

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

on: 上:

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

Because methodO() is not expected to return Exception instance (as in your example) but it is expected to be thrown (by using closure). 因为不希望methodO() 返回 Exception实例(如您的示例),但methodO()抛出 (通过使用闭包)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM