Search code examples
exceptionmockingspockoperationratpack

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.

I'm writing the unit-test with Spock in Groovy.

There are class A, and 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

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

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

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'

Solution

  • 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).