Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import org.junit.Rule;
- import org.junit.Test;
- import org.junit.rules.ExpectedException;
- import static org.junit.Assert.assertEquals;
- import static org.junit.Assert.assertFalse;
- import static org.junit.Assert.assertTrue;
- import static org.junit.Assert.fail;
- public class RetryTest {
- private static final String RESULT = "operation result";
- class State {
- public boolean operationCalled = false, preRetryCalled = false;
- public int operationCalledTimes = 0, preRetryCalledTimes = 0;
- }
- @Rule
- public ExpectedException thrown = ExpectedException.none();
- @Test
- public void noRetriesNeeded() throws Exception {
- String result = Retry.retry(
- // 1 retry
- 1,
- // operation
- new Function0<String>() {
- public String apply() {
- return RESULT;
- }
- },
- // checker
- new Function1<String, Boolean>() {
- public Boolean apply(String checkedResult) {
- return true;
- }
- },
- // pre-retry
- new Function0<Void>() {
- public Void apply() {
- fail("wrong pre-retry");
- return null;
- }
- },
- // use default error message
- null
- );
- assertEquals(RESULT, result);
- }
- @Test
- public void succeededAfterRetry() throws Exception {
- final State state = new State();
- String result = Retry.retry(
- // 1 retry max
- 1,
- // operation
- new Function0<String>() {
- public String apply() {
- return RESULT;
- }
- },
- // checker
- new Function1<String, Boolean>() {
- public Boolean apply(String checkedResult) {
- final boolean result;
- state.operationCalledTimes++;
- if (state.operationCalled) {
- result = true;
- } else {
- state.operationCalled = true;
- result = false;
- }
- return result;
- }
- },
- // pre-retry
- new Function0<Void>() {
- public Void apply() {
- state.preRetryCalledTimes++;
- if (state.preRetryCalled) {
- fail("pre-retry already called");
- } else {
- state.preRetryCalled = true;
- }
- return null;
- }
- },
- // use default error message
- null
- );
- assertEquals(RESULT, result);
- assertTrue(state.operationCalled);
- assertTrue(state.preRetryCalled);
- assertEquals(2, state.operationCalledTimes);
- assertEquals(1, state.preRetryCalledTimes);
- }
- @Test
- public void failedAfterRetriesExhausted() throws Exception {
- final String errorMessage = "oops";
- thrown.expect(Exception.class);
- thrown.expectMessage(errorMessage);
- final State state = new State();
- Retry.retry(
- // 5 retries
- 5,
- // operation
- new Function0<String>() {
- public String apply() {
- return RESULT;
- }
- },
- // checker
- new Function1<String, Boolean>() {
- public Boolean apply(String checkedResult) {
- return false;
- }
- },
- // pre-retry
- new Function0<Void>() {
- public Void apply() {
- state.preRetryCalledTimes++;
- assertFalse(state.preRetryCalledTimes > 5);
- return null;
- }
- },
- // custom error message
- errorMessage
- );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment