Question: I'm using the Spock Framework to test some Java classes. One thing I need to do is add a delay to a Stub method that I'm calling, in order to simulate a long-running method. Is this possible?

This looks possible using Mockito: [Can I delay a stubbed method response with Mockito?](https://stackoverflow.com/questions/12813881/can-i-delay-a-stubbed-method-response-with-mockito). Is it possible using Spock?

Answer: 
Spock is a Groovy tool. Therefore, you have some syntactic sugar and do not need a tedious try-catch around `Thread.sleep`. You simply write:

```java
// Sleep for 2.5 seconds
sleep 2500

```

Your test could look like this:

```java
class Calculator {
  int multiply(int a, int b) {
    return a * b
  }
}

```

```java
class MyClass {
  private final Calculator calculator

  MyClass(Calculator calculator) {
    this.calculator = calculator
  }

  int calculate() {
    return calculator.multiply(3, 4)
  }
}

```

```java
import spock.lang.Specification

import static java.lang.System.currentTimeMillis

class WaitingTest extends Specification {
  static final int SLEEP_MILLIS = 250

  def "verify slow multiplication"() {
    given:
    Calculator calculator = Stub() {
      multiply(_, _) >> {
        sleep SLEEP_MILLIS
        42
      }
    }
    def myClass = new MyClass(calculator)
    def startTime = currentTimeMillis()

    expect:
    myClass.calculate() == 42
    currentTimeMillis() - startTime > SLEEP_MILLIS
  }
}

```

[Try it in the Groovy web console.](https://gwc-experiment.appspot.com/?g=groovy_2_5&codez=eJxtkTFvwjAQhXf_ihNTUtGoonSpFBbEgARSpSB1RCa90GsdJ7KdQIT473WMEwJlse7il8_v3VFeFsqALov0NxJc7qOkxJQySrmhQjJGXmBsn8IPr7mXNdpgHqWVUijNhnJckxCkGUsF1xo-ORmS-w1qA3g0KL803KDhxKDDZiS5AJIGktVi8bFdL1erZQIxTN5emJV9YQajGhVlDWhRHCCvhKFSeNQoCB0NYE81yndXzrlIK8FNoSC9ljEkptr1euhITbAdwzaE2ay_se4EYnljqb-aTnx5ZteztZk3c5c_BokHWF-64Oog7JU2u3KDs9p_YwxC5oR4tDMzl0QeHXUwtDHiuLPyAAHPg0dm90HO7Nwty9t00UtFtWX7nTycYmutS_ZQ0I3XfNPVrpv-ANI6sEe79WGiy58KTaXkQB71i3odwzS89T8wcfLIXt42fOy-7e7oHJ5g50l_Jpn2pw)
> 
> One thing I need to do is add a delay to a Stub method that I'm
> calling, in order to simulate a long-running method. Is this possible?
> 
> 
> 

It is difficult to say for sure if this is the right thing to do without knowing more about the situation under test but if you are executing a method and want that to result in tying up the current thread for a period to simulate doing work, your mock method could invoke `Thread.sleep`.