Guest User

Untitled

a guest
Jan 19th, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. public class Retry implements TestRule {
  2. private int retryCount = 10;
  3.  
  4. @Override
  5. public Statement apply(Statement base, Description description) {
  6. return new Statement() {
  7. public void evaluate() throws Throwable {
  8. RetryCount annotation = description.getAnnotation(RetryCount.class);
  9. // Problem is here, the annotation is always null!
  10. int retries = (annotation != null) ? annotation.retries() : retryCount;
  11.  
  12. // keep track of the last failure to include it in our failure later
  13. AssertionError lastFailure = null;
  14. for (int i = 0; i < retries; i++) {
  15. try {
  16. // call wrapped statement and return if successful
  17. base.evaluate();
  18. return;
  19. } catch (AssertionError err) {
  20. lastFailure = err;
  21. }
  22. }
  23. // give meaningful message and include last failure for the
  24. // error trace
  25. throw new AssertionError("Gave up after " + retries + " tries", lastFailure);
  26. }
  27. };
  28. }
  29.  
  30. // the annotation for method-based retries
  31. public static @interface RetryCount {
  32. public int retries() default 1;
  33. }
  34. }
  35.  
  36. public class UnreliableServiceUnitTest {
  37. private UnreliableService sut = new UnreliableService();
  38.  
  39. @Rule
  40. public Retry retry = new Retry();
  41.  
  42. @Test
  43. @RetryCount(retries=5) // here it is
  44. public void worksSometimes() {
  45. boolean worked = sut.workSometimes();
  46. assertThat(worked, is(true));
  47. }
  48. }
  49.  
  50. public class UnreliableService {
  51. private static Random RANDOM = new Random();
  52.  
  53. // needs at least two calls
  54. private static int COUNTER = RANDOM.nextInt(8) + 2;
  55.  
  56. public boolean workSometimes() {
  57. if (--COUNTER == 0) {
  58. COUNTER = RANDOM.nextInt(8) + 2;
  59. return true;
  60. }
  61. return false;
  62. }
  63. }
Add Comment
Please, Sign In to add comment