2
votes

I have a spock test, which calls some service:

when:
def x = service.call()

then:
!x

Inside service I have:

def call() {
  try {
    doCall() // method, which throws an exception
  } catch (e) {
    false
  }
}

So I expect method to return false and test to pass. However, test invocation from IDE prints stacktrace of the exception, though it is catched.

Purpose of the test is not to know whether exception was thrown, but just assert returned result is false, so I don't want to use Specification.thrown

1
what exception do you have? catch(e) catches only Exception and descendants. - daggett
My exception is GroovyRuntimeException - Rahul
Btw, post a full stack trace please. Otherwise it is impossible to guess what might be the real cause of the issue. - Szymon Stepniak
What Spock version, Groovy version an Java version are you using? In Spock 1.1 and 1.2 under Java 8 the behavior is correct. And as @SzymonStepniak said - post also the full stack trace. - cgrim
The problem is in groovyx.net.http.HTTPBuilder:494 (0.7.1 version). It prints warn message and passes caught exception there, which prints stacktrace and then rethrows it - Rahul

1 Answers

0
votes

First of all - check what specific exception gets thrown and gets outside the try-catch block. You have to be aware that following code in Groovy:

try {
   // do something
} catch (e) {
   // do something with exception
}

is an equivalent of:

try {
   // do something
} catch (Exception e) {
   // do something with exception
}

It means that java.lang.Throwable and all its children classes (except java.lang.Exception) are not caught inside your try catch. For instance:

def call() {
    try {
        throw new Error('Something wrong happened')
    } catch (e) {
        false
    }
}

This exception won't get caught by try-catch and you will see something like this in the console log:

java.lang.Error: Something wrong happened

    at com.github.wololock.micronaut.TestSpec$Service.call(TestSpec.groovy:22)
    at com.github.wololock.micronaut.TestSpec.test(TestSpec.groovy:13)

It happens, because java.lang.Error extends java.lang.Throwable and it is not a child class of java.lang.Exception.

If you want to catch all possible exceptions that may happened to your code you would have to use Throwable inside the catch block, something like this:

def call() {
    try {
        throw new Error('Something wrong happened')
    } catch (Throwable e) {
        false
    }
}