Skip to content

Instantly share code, notes, and snippets.

@paliwodar
Last active May 24, 2018 10:58
Show Gist options
  • Save paliwodar/e0b393cec160ab26b12bb76eba863309 to your computer and use it in GitHub Desktop.
Save paliwodar/e0b393cec160ab26b12bb76eba863309 to your computer and use it in GitHub Desktop.
A simple implementation of retry mechanism in Groovy
class SpecFile extends Specification {
def "Order delivery example test case"() {
given:
def product = createProduct()
expect:
retry { user pay product } waiting 500 upTo 3000 until {
it?.responseData?.status == "success"
}
when:
def delivery = merchant ship product
then:
with(delivery.responseData) {
productId == product.id
delivery.address == user.address
status == "success"
// ...
}
}
}
class RetryUtil {
Closure action
long sleep = 1000
long timeout = 10000
static def retry(Closure action) {
new RetryUtil(action: action)
}
def waiting(long sleep) {
this.sleep = sleep;
return this
}
def upTo(long timeout) {
this.timeout = timeout
return this
}
def until(Closure<Boolean> predicate) {
def start = currentTimeMillis()
def iterator = [hasNext: { currentTimeMillis() - start < timeout },
next : { sleep(sleep); action() }] as Iterator
iterator.find predicate
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment