From ce486813c8b248afc4abdc223784d0d31942e527 Mon Sep 17 00:00:00 2001 From: Alberto Scotto Date: Mon, 30 May 2016 15:37:44 +0100 Subject: [PATCH 1/2] Refactor RetryRule: no need to use an AtomicInteger Declare retryCount as final, and use a local variable instead. --- .../com/yourcompany/TestRules/RetryRule.java | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-) diff --git a/src/test/java/com/yourcompany/TestRules/RetryRule.java b/src/test/java/com/yourcompany/TestRules/RetryRule.java index b33d8da..bf5ec2f 100644 --- a/src/test/java/com/yourcompany/TestRules/RetryRule.java +++ b/src/test/java/com/yourcompany/TestRules/RetryRule.java @@ -1,24 +1,18 @@ package com.yourcompany.TestRules; - -import org.junit.rules.MethodRule; import org.junit.rules.TestRule; import org.junit.runner.Description; -import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement; -import java.util.concurrent.atomic.AtomicInteger; - /** * Created by mehmetgerceker on 12/7/15. */ public class RetryRule implements TestRule { - private AtomicInteger retryCount; + private final int retryCount; public RetryRule(int retries){ - super(); - this.retryCount = new AtomicInteger(retries); + this.retryCount = retries; } @Override @@ -31,17 +25,16 @@ public void evaluate() throws Throwable { Throwable caughtThrowable = null; // implement retry logic here - while (retryCount.getAndDecrement() > 0) { + int i = retryCount; + while (i-- > 0) { try { base.evaluate(); return; } catch (Throwable t) { - if (retryCount.get() > 0 && description.getAnnotation(Retry.class)!= null) { + if (i > 0 && description.getAnnotation(Retry.class)!= null) { caughtThrowable = t; System.err.println(description.getDisplayName() + - ": Failed, " + - retryCount.toString() + - "retries remain"); + ": Failed, " + i + "retries remain"); } else { throw caughtThrowable; } From 6ce8aae5e8cc6eb244633d0ca22b972948b964d7 Mon Sep 17 00:00:00 2001 From: Alberto Scotto Date: Mon, 30 May 2016 15:40:12 +0100 Subject: [PATCH 2/2] RetryRule: fix NPE caughtThrowable could have been not initialized. E.g. if retryCount is 1, and the first execution failed, it would have thrown null. --- src/test/java/com/yourcompany/TestRules/RetryRule.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/yourcompany/TestRules/RetryRule.java b/src/test/java/com/yourcompany/TestRules/RetryRule.java index bf5ec2f..ed4289a 100644 --- a/src/test/java/com/yourcompany/TestRules/RetryRule.java +++ b/src/test/java/com/yourcompany/TestRules/RetryRule.java @@ -31,8 +31,8 @@ public void evaluate() throws Throwable { base.evaluate(); return; } catch (Throwable t) { + caughtThrowable = t; if (i > 0 && description.getAnnotation(Retry.class)!= null) { - caughtThrowable = t; System.err.println(description.getDisplayName() + ": Failed, " + i + "retries remain"); } else {