1 package host.exp.exponent.utils 2 3 import org.junit.rules.TestRule 4 import org.junit.runner.Description 5 import org.junit.runners.model.Statement 6 7 class RetryTestRule(private val retryCount: Int) : TestRule { 8 override fun apply(base: Statement, description: Description): Statement { 9 return statement(base, description) 10 } 11 12 private fun statement(base: Statement, description: Description): Statement { 13 return object : Statement() { 14 @Throws(Throwable::class) 15 override fun evaluate() { 16 var caughtThrowable: Throwable? = null 17 for (i in 0 until retryCount) { 18 try { 19 base.evaluate() 20 return 21 } catch (t: Throwable) { 22 caughtThrowable = t 23 System.err.println(description.displayName + ": run " + (i + 1) + " failed") 24 } 25 } 26 System.err.println(description.displayName + ": giving up after " + retryCount + " failures") 27 throw caughtThrowable!! 28 } 29 } 30 } 31 } 32