Operations { public static void doWithRetries( Runnable action, int numberOfRetries, int sleepInMillisec ){ int triesLeft = numberOfRetries; while (true) { try { action.run(); return; } catch (Exception|AssertionError e) { triesLeft-=1; if (triesLeft<=0) { throw e; } try { sleep(sleepInMillisec); } catch (InterruptedException intEx) { throw new RuntimeException(intEx); } } } }  static void doWithRetries(
            Runnable action,
            int numberOfRetries,
            int sleepInMillisec
            ); static T doWithRetries(
            Callable<T> action,
            int numberOfRetries,
            int sleepInMillisec
    );  }
@Test public void clickWithRetriesSuccess() throws Exception { when(browser.clickOn(any())).thenThrow(NoSuchElementException.class).thenThrow(NoSuchElementException.class).thenReturn(webel); Operations.doWithRetries(() -> browser.clickOn(div), 5, 10); verify(browser, times(3)).clickOn(div); }
@Test public void clickWithRetriesFailure() throws Exception { when(browser.clickOn(any())).thenThrow(Exception.class).thenThrow(IOException.class).thenThrow(NoSuchElementException.class); try { Operations.doWithRetries(() -> browser.clickOn(div), 3, 10); } catch ( NoSuchElementException e) { verify(browser, times(3)).clickOn(div); return; } fail("expected to throw NoSuchElementException"); }