Refactor Vavr Future (#3349)

This commit is contained in:
Grzegorz Piwowarek 2018-01-04 17:21:16 +02:00 committed by GitHub
parent b54440ddb3
commit 2afc7dc623
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 92 additions and 135 deletions

View File

@ -1,20 +0,0 @@
package com.baeldung.vavr.future;
public class Util {
public static String appendData(String initial) {
return initial + "Baeldung!";
}
public static int divideByZero(int num) {
return num / 0;
}
public static String getSubstringMinusOne(String s) {
return s.substring(-1);
}
public static String getSubstringMinusTwo(String s) {
return s.substring(-2);
}
}

View File

@ -1,119 +1,102 @@
package com.baeldung.vavr.future; package com.baeldung.vavr.future;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import org.junit.Test;
import io.vavr.Tuple; import io.vavr.Tuple;
import io.vavr.Tuple2;
import io.vavr.concurrent.Future; import io.vavr.concurrent.Future;
import io.vavr.control.Option; import io.vavr.control.Option;
import io.vavr.control.Try; import io.vavr.control.Try;
import org.junit.Test;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import static java.util.concurrent.Executors.newSingleThreadExecutor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class FutureTest { public class FutureTest {
private static final String error = "Failed to get underlying value."; private static final String error = "Failed to get underlying value.";
private static final String HELLO = "Welcome to Baeldung!";
@Test @Test
public void whenChangeExecutorService_thenCorrect() throws InterruptedException { public void whenChangeExecutorService_thenCorrect() {
String initialValue = "Welcome to "; String result = Future.of(newSingleThreadExecutor(), () -> HELLO)
Future<String> resultFuture = Future.of( .getOrElse(error);
Executors.newSingleThreadExecutor(),
() -> Util.appendData(initialValue));
Thread.sleep(20);
String result = resultFuture.getOrElse(error);
assertThat(result).isEqualTo("Welcome to Baeldung!"); assertThat(result)
.isEqualTo(HELLO);
} }
@Test @Test
public void whenAppendData_thenCorrect1() throws InterruptedException { public void whenAppendData_thenCorrect1() {
String initialValue = "Welcome to "; String result = Future.of(() -> HELLO)
Future<String> resultFuture = Future.of(() -> Util.appendData(initialValue)); .getOrElse(error);
Thread.sleep(20);
String result = resultFuture.getOrElse(new String(error));
assertThat(result).isEqualTo("Welcome to Baeldung!"); assertThat(result)
.isEqualTo(HELLO);
} }
@Test @Test
public void whenAppendData_thenCorrect2() throws InterruptedException { public void whenAppendData_thenCorrect2() {
String initialValue = "Welcome to "; Future<String> resultFuture = Future.of(() -> HELLO)
Future<String> resultFuture = Future.of(() -> Util.appendData(initialValue)); .await();
Thread.sleep(20);
resultFuture.await();
Option<Try<String>> futureOption = resultFuture.getValue(); Option<Try<String>> futureOption = resultFuture.getValue();
Try<String> futureTry = futureOption.get(); String result = futureOption.get().getOrElse(error);
String result = futureTry.getOrElse(error);
assertThat(result).isEqualTo("Welcome to Baeldung!"); assertThat(result)
.isEqualTo(HELLO);
} }
@Test @Test
public void whenAppendData_thenSuccess() throws InterruptedException { public void whenAppendData_thenSuccess() {
String initialValue = "Welcome to "; String result = Future.of(() -> HELLO)
Future<String> resultFuture = Future.of(() -> Util.appendData(initialValue))
.onSuccess(finalResult -> System.out.println("Successfully Completed - Result: " + finalResult)) .onSuccess(finalResult -> System.out.println("Successfully Completed - Result: " + finalResult))
.onFailure(finalResult -> System.out.println("Failed - Result: " + finalResult)); .onFailure(finalResult -> System.out.println("Failed - Result: " + finalResult))
Thread.sleep(20); .getOrElse(error);
String result = resultFuture.getOrElse(error);
assertThat(result).isEqualTo("Welcome to Baeldung!"); assertThat(result)
.isEqualTo(HELLO);
} }
@Test @Test
public void whenChainingCallbacks_thenCorrect() throws InterruptedException { public void whenChainingCallbacks_thenCorrect() {
String initialValue = "Welcome to "; Future.of(() -> HELLO)
Future<String> resultFuture = Future.of(() -> Util.appendData(initialValue)) .andThen(r -> System.out.println("Completed - 1: " + r))
.andThen(finalResult -> System.out.println("Completed - 1: " + finalResult)) .andThen(r -> System.out.println("Completed - 2: " + r));
.andThen(finalResult -> System.out.println("Completed - 2: " + finalResult));
Thread.sleep(20);
String result = resultFuture.getOrElse(error);
assertThat(result).isEqualTo("Welcome to Baeldung!");
} }
@Test @Test
public void whenCallAwait_thenCorrect() throws InterruptedException { public void whenCallAwait_thenCorrect() {
String initialValue = "Welcome to "; Future<String> resultFuture = Future.of(() -> HELLO)
Future<String> resultFuture = Future.of(() -> Util.appendData(initialValue)); .await();
Thread.sleep(20); String result = resultFuture.getValue().get().getOrElse(error);
resultFuture = resultFuture.await();
String result = resultFuture.getOrElse(error);
assertThat(result).isEqualTo("Welcome to Baeldung!"); assertThat(result)
.isEqualTo(HELLO);
} }
@Test @Test
public void whenDivideByZero_thenGetThrowable1() throws InterruptedException { public void whenDivideByZero_thenGetThrowable1() {
Future<Integer> resultFuture = Future.of(() -> Util.divideByZero(10)); Future<Integer> resultFuture = Future.of(() -> 10 / 0);
Thread.sleep(20);
Future<Throwable> throwableFuture = resultFuture.failed();
Throwable throwable = throwableFuture.getOrElse(new Throwable());
assertThat(throwable.getMessage()).isEqualTo("/ by zero"); assertThatThrownBy(resultFuture::get)
.isInstanceOf(ArithmeticException.class);
} }
@Test @Test
public void whenDivideByZero_thenGetThrowable2() throws InterruptedException { public void whenDivideByZero_thenGetThrowable2() {
Future<Integer> resultFuture = Future.of(() -> Util.divideByZero(10)); Future<Integer> resultFuture = Future.of(() -> 10 / 0)
Thread.sleep(20); .await();
resultFuture.await();
Option<Throwable> throwableOption = resultFuture.getCause();
Throwable throwable = throwableOption.getOrElse(new Throwable());
assertThat(throwable.getMessage()).isEqualTo("/ by zero"); assertThat(resultFuture.getCause().get().getMessage())
.isEqualTo("/ by zero");
} }
@Test @Test
public void whenDivideByZero_thenCorrect() throws InterruptedException { public void whenDivideByZero_thenCorrect() {
Future<Integer> resultFuture = Future.of(() -> Util.divideByZero(10)); Future<Integer> resultFuture = Future.of(() -> 10 / 0)
Thread.sleep(20); .await();
resultFuture.await();
assertThat(resultFuture.isCompleted()).isTrue(); assertThat(resultFuture.isCompleted()).isTrue();
assertThat(resultFuture.isSuccess()).isFalse(); assertThat(resultFuture.isSuccess()).isFalse();
@ -121,76 +104,70 @@ public class FutureTest {
} }
@Test @Test
public void whenAppendData_thenFutureNotEmpty() throws InterruptedException { public void whenAppendData_thenFutureNotEmpty() {
String initialValue = "Welcome to "; Future<String> resultFuture = Future.of(() -> HELLO)
Future<String> resultFuture = Future.of(() -> Util.appendData(initialValue)); .await();
Thread.sleep(20);
resultFuture.await();
assertThat(resultFuture.isEmpty()).isFalse(); assertThat(resultFuture.isEmpty())
.isFalse();
} }
@Test @Test
public void whenCallZip_thenCorrect() throws InterruptedException { public void whenCallZip_thenCorrect() {
Future<Tuple2<String, Integer>> future = Future.of(() -> "John") Future<String> f1 = Future.of(() -> "hello1");
.zip(Future.of(() -> new Integer(5))); Future<String> f2 = Future.of(() -> "hello2");
Thread.sleep(20);
future.await();
assertThat(future.getOrElse(new Tuple2<String, Integer>(error, 0))) assertThat(f1.zip(f2).get())
.isEqualTo(Tuple.of("John", new Integer(5))); .isEqualTo(Tuple.of("hello1", "hello2"));
} }
@Test @Test
public void whenConvertToCompletableFuture_thenCorrect() throws InterruptedException, ExecutionException { public void whenConvertToCompletableFuture_thenCorrect() throws InterruptedException, ExecutionException {
String initialValue = "Welcome to "; CompletableFuture<String> convertedFuture = Future.of(() -> HELLO)
Future<String> resultFuture = Future.of(() -> Util.appendData(initialValue)); .toCompletableFuture();
Thread.sleep(20);
CompletableFuture<String> convertedFuture = resultFuture.toCompletableFuture();
assertThat(convertedFuture.get()).isEqualTo("Welcome to Baeldung!"); assertThat(convertedFuture.get())
.isEqualTo(HELLO);
} }
@Test @Test
public void whenCallMap_thenCorrect() throws InterruptedException { public void whenCallMap_thenCorrect() {
Future<String> futureResult = Future.of(() -> new StringBuilder("from Baeldung")) Future<String> futureResult = Future.of(() -> "from Baeldung")
.map(a -> "Hello " + a); .map(a -> "Hello " + a)
Thread.sleep(20); .await();
futureResult.await();
assertThat(futureResult.getOrElse(error)).isEqualTo("Hello from Baeldung"); assertThat(futureResult.get())
.isEqualTo("Hello from Baeldung");
} }
@Test @Test
public void whenFutureFails_thenGetErrorMessage() throws InterruptedException { public void whenFutureFails_thenGetErrorMessage() {
Future<String> resultFuture = Future.of(() -> Util.getSubstringMinusOne("Hello")); Future<String> future = Future.of(() -> "Hello".substring(-1))
Thread.sleep(20); .recover(x -> "fallback value");
Future<String> errorMessageFuture = resultFuture.recover(Throwable::getMessage);
String errorMessage = errorMessageFuture.getOrElse(error);
assertThat(errorMessage).isEqualTo("String index out of range: -1"); assertThat(future.get())
.isEqualTo("fallback value");
} }
@Test @Test
public void whenFutureFails_thenGetAnotherFuture() throws InterruptedException { public void whenFutureFails_thenGetAnotherFuture() {
Future<String> resultFuture = Future.of(() -> Util.getSubstringMinusOne("Hello")); Future<String> future = Future.of(() -> "Hello".substring(-1))
Thread.sleep(20); .recoverWith(x -> Future.of(() -> "fallback value"));
Future<String> errorMessageFuture = resultFuture.recoverWith(a -> Future.of(a::getMessage));
String errorMessage = errorMessageFuture.getOrElse(error);
assertThat(errorMessage).isEqualTo("String index out of range: -1"); assertThat(future.get())
.isEqualTo("fallback value");
} }
@Test @Test
public void whenBothFuturesFail_thenGetErrorMessage() throws InterruptedException { public void whenBothFuturesFail_thenGetErrorMessage() {
Future<String> future1 = Future.of(() -> Util.getSubstringMinusOne("Hello")); Future<String> f1 = Future.of(() -> "Hello".substring(-1));
Future<String> future2 = Future.of(() -> Util.getSubstringMinusTwo("Hello")); Future<String> f2 = Future.of(() -> "Hello".substring(-2));
Thread.sleep(20);
Future<String> errorMessageFuture = future1.fallbackTo(future2); Future<String> errorMessageFuture = f1.fallbackTo(f2);
Future<Throwable> errorMessage = errorMessageFuture.failed(); Future<Throwable> errorMessage = errorMessageFuture.failed();
assertThat( assertThat(
errorMessage.getOrElse(new Throwable()).getMessage()) errorMessage.get().getMessage())
.isEqualTo("String index out of range: -1"); .isEqualTo("String index out of range: -1");
} }
} }