Skip to content

Commit 1ddd46f

Browse files
hunghoangadamd1985
authored andcommitted
BAEL-1080 Introduction to Future in Vavr (eugenp#2627)
* Add example of different types of bean injection * BAEL-1080 Introduction to Future and Pattern Matching in Vavr * Update future with Pattern Matching * remove unused files * Update future unit test of cancelled Future * remove unused import * delete unused files * using await() on future to wait until future completed instead of using while(true) * Add Awaitability to FutureTest, avoid using while loop * format code * add some static void method that print the result to console
1 parent c7f180f commit 1ddd46f

1 file changed

Lines changed: 115 additions & 29 deletions

File tree

‎vavr/src/test/java/com/baeldung/vavr/future/FutureUnitTest.java‎

Lines changed: 115 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -5,17 +5,23 @@
55
import static io.vavr.API.Match;
66
import static io.vavr.Predicates.exists;
77
import static io.vavr.Predicates.forAll;
8-
import static org.awaitility.Awaitility.await;
98
import static org.junit.Assert.assertEquals;
109
import static org.junit.Assert.assertTrue;
1110

1211
import java.util.concurrent.CancellationException;
12+
import java.util.function.Consumer;
1313
import java.util.function.Predicate;
1414

1515
import org.junit.Test;
16+
import org.mockito.Mockito;
17+
import org.mockito.internal.verification.VerificationModeFactory;
18+
import org.mockito.verification.Timeout;
1619

20+
import io.vavr.Tuple;
21+
import io.vavr.Tuple2;
1722
import io.vavr.collection.List;
1823
import io.vavr.concurrent.Future;
24+
import io.vavr.control.Try;
1925

2026
public class FutureUnitTest {
2127

@@ -26,8 +32,7 @@ public class FutureUnitTest {
2632
public void givenFunctionReturnInteger_WhenCallWithFuture_ShouldReturnFunctionValue() {
2733
Future<Integer> future = Future.of(() -> 1);
2834

29-
assertEquals(1, future.get()
30-
.intValue());
35+
assertEquals(1, future.get().intValue());
3136
}
3237

3338
@Test
@@ -57,42 +62,37 @@ public void givenAFutureReturnZero_WhenCheckFutureWithExistEvenValue_ShouldRetur
5762

5863
@Test
5964
public void givenFunction_WhenCallWithFutureAndRegisterConsumerForSuccess_ShouldCallConsumerToStoreValue() {
60-
final int[] store = new int[] { 0 };
6165
Future<Integer> future = Future.of(() -> 1);
62-
future.onSuccess(i -> {
63-
store[0] = i;
64-
});
65-
await().until(() -> store[0] == 1);
66+
MockConsumer consumer = Mockito.mock(MockConsumer.class);
67+
future.onSuccess(consumer);
68+
Mockito.verify(consumer, new Timeout(1000, VerificationModeFactory.times(1))).accept(1);
6669
}
6770

6871
@Test
6972
public void givenFunctionThrowException_WhenCallWithFutureAndRegisterConsumerForFailer_ShouldCallConsumerToStoreException() {
70-
final Throwable[] store = new Throwable[] { null };
7173
Future<String> future = Future.of(() -> getResourceThrowException(""));
72-
future.onFailure(err -> store[0] = err);
73-
await().until(() -> RuntimeException.class.isInstance(store[0]));
74+
MockThrowableConsumer consumer = Mockito.mock(MockThrowableConsumer.class);
75+
future.onFailure(consumer);
76+
Mockito.verify(consumer, new Timeout(1000, VerificationModeFactory.times(1))).accept(Mockito.any());
7477
}
7578

7679
@Test
7780
public void givenAFuture_WhenAddAndThenConsumer_ShouldCallConsumerWithResultOfFutureAction() {
78-
int[] store1 = new int[1];
79-
int[] store2 = new int[1];
81+
MockTryConsumer consumer1 = Mockito.mock(MockTryConsumer.class);
82+
MockTryConsumer consumer2 = Mockito.mock(MockTryConsumer.class);
8083
Future<Integer> future = Future.of(() -> 1);
81-
Future<Integer> andThenFuture = future.andThen(i -> store1[0] = i.get() + 1)
82-
.andThen(i -> store2[0] = store1[0] + 1);
84+
Future<Integer> andThenFuture = future.andThen(consumer1).andThen(consumer2);
8385
andThenFuture.await();
84-
85-
assertEquals(2, store1[0]);
86-
assertEquals(3, store2[0]);
86+
Mockito.verify(consumer1, VerificationModeFactory.times(1)).accept(Try.success(1));
87+
Mockito.verify(consumer2, VerificationModeFactory.times(1)).accept(Try.success(1));
8788
}
8889

8990
@Test
9091
public void givenAFailureFuture_WhenCallOrElseFunction_ShouldReturnNewFuture() {
9192
Future<Integer> future = Future.failed(new RuntimeException());
9293
Future<Integer> future2 = future.orElse(Future.of(() -> 2));
9394

94-
assertEquals(2, future2.get()
95-
.intValue());
95+
assertEquals(2, future2.get().intValue());
9696
}
9797

9898
@Test(expected = CancellationException.class)
@@ -124,17 +124,46 @@ public void givenAFuture_WhenCallFallBackWithFailureFuture_ShouldReturnValueOfFa
124124
Future<String> future = Future.failed(new RuntimeException());
125125
Future<String> fallbackFuture = Future.of(() -> expectedResult);
126126
Future<String> futureResult = future.fallbackTo(fallbackFuture);
127-
futureResult.await();
128127

129128
assertEquals(expectedResult, futureResult.get());
130129
}
130+
131+
@Test
132+
public void givenAFuture_WhenTransformByAddingOne_ShouldReturn() {
133+
Future<Object> future = Future.of(() -> 1).transformValue(f -> Try.of(() -> "Hello: " + f.get()));
134+
135+
assertEquals("Hello: 1", future.get());
136+
}
137+
138+
@Test
139+
public void givenAFutureOfInt_WhenMapToString_ShouldCombineAndReturn() {
140+
Future<String> future = Future.of(()->1).map(i -> "Hello: " + i);
141+
142+
assertEquals("Hello: 1", future.get());
143+
}
144+
145+
@Test
146+
public void givenAFutureOfInt_WhenFlatMapToString_ShouldCombineAndReturn() {
147+
Future<Object> futureMap = Future.of(() -> 1).flatMap((i) -> Future.of(() -> "Hello: " + i));
148+
149+
assertEquals("Hello: 1", futureMap.get());
150+
}
151+
152+
@Test
153+
public void givenAFutureOf2String_WhenZip_ShouldReturnTupleOf2String() {
154+
Future<Tuple2<String, String>> future = Future.of(() -> "hello").zip(Future.of(() -> "world"));
155+
156+
assertEquals(Tuple.of("hello", "world"), future.get());
157+
}
131158

132159
@Test
133160
public void givenGetResourceWithFuture_WhenWaitAndMatchWithPredicate_ShouldReturnSuccess() {
134161
String url = "http://resource";
135162
Future<String> future = Future.of(() -> getResource(url));
136163
future.await();
137-
String s = Match(future).of(Case($(future0 -> future0.isSuccess()), SUCCESS), Case($(), FAILURE));
164+
String s = Match(future).of(
165+
Case($(future0 -> future0.isSuccess()), SUCCESS),
166+
Case($(), FAILURE));
138167

139168
assertEquals(SUCCESS, s);
140169
}
@@ -143,7 +172,9 @@ public void givenGetResourceWithFuture_WhenWaitAndMatchWithPredicate_ShouldRetur
143172
public void givenAFailedFuture_WhenWaitAndMatchWithPredicateCheckSuccess_ShouldReturnFailed() {
144173
Future<Integer> future = Future.failed(new RuntimeException());
145174
future.await();
146-
String s = Match(future).of(Case($(future0 -> future0.isSuccess()), SUCCESS), Case($(), FAILURE));
175+
String s = Match(future).of(
176+
Case($(future0 -> future0.isSuccess()), SUCCESS),
177+
Case($(), FAILURE));
147178

148179
assertEquals(FAILURE, s);
149180
}
@@ -155,7 +186,10 @@ public void givenAFuture_WhenMatchWithFuturePredicate_ShouldReturnSuccess() {
155186
return 1;
156187
});
157188
Predicate<Future<Integer>> predicate = f -> f.exists(i -> i % 2 == 1);
158-
String s = Match(future).of(Case($(predicate), "Even"), Case($(), "Odd"));
189+
190+
String s = Match(future).of(
191+
Case($(predicate), "Even"),
192+
Case($(), "Odd"));
159193

160194
assertEquals("Even", s);
161195
}
@@ -164,7 +198,9 @@ public void givenAFuture_WhenMatchWithFuturePredicate_ShouldReturnSuccess() {
164198
public void givenAListOfFutureReturnFist3Integers_WhenMatchWithExistEvenNumberPredicate_ShouldReturnSuccess() {
165199
List<Future<Integer>> futures = getFutureOfFirst3Number();
166200
Predicate<Future<Integer>> predicate0 = future -> future.exists(i -> i % 2 == 0);
167-
String s = Match(futures).of(Case($(exists(predicate0)), "Even"), Case($(), "Odd"));
201+
String s = Match(futures).of(
202+
Case($(exists(predicate0)), "Even"),
203+
Case($(), "Odd"));
168204

169205
assertEquals("Even", s);
170206
}
@@ -173,7 +209,9 @@ public void givenAListOfFutureReturnFist3Integers_WhenMatchWithExistEvenNumberPr
173209
public void givenAListOfFutureReturnFist3Integers_WhenMatchWithForAllNumberBiggerThanZeroPredicate_ShouldReturnSuccess() {
174210
List<Future<Integer>> futures = getFutureOfFirst3Number();
175211
Predicate<Future<Integer>> predicate0 = future -> future.exists(i -> i > 0);
176-
String s = Match(futures).of(Case($(forAll(predicate0)), "Positive numbers"), Case($(), "None"));
212+
String s = Match(futures).of(
213+
Case($(forAll(predicate0)), "Positive numbers"),
214+
Case($(), "None"));
177215

178216
assertEquals("Positive numbers", s);
179217
}
@@ -182,13 +220,19 @@ public void givenAListOfFutureReturnFist3Integers_WhenMatchWithForAllNumberBigge
182220
public void givenAListOfFutureReturnFist3Integers_WhenMatchWithForAllNumberSmallerThanZeroPredicate_ShouldReturnFailed() {
183221
List<Future<Integer>> futures = getFutureOfFirst3Number();
184222
Predicate<Future<Integer>> predicate0 = future -> future.exists(i -> i < 0);
185-
String s = Match(futures).of(Case($(forAll(predicate0)), "Negative numbers"), Case($(), "None"));
223+
String s = Match(futures).of(
224+
Case($(forAll(predicate0)), "Negative numbers"),
225+
Case($(), "None"));
186226

187227
assertEquals("None", s);
188228
}
189229

190-
private String getResource(String url) throws InterruptedException {
191-
Thread.sleep(10);
230+
private String getResource(String url) {
231+
try {
232+
Thread.sleep(10);
233+
} catch (InterruptedException e) {
234+
throw new RuntimeException(e);
235+
}
192236
return "Content from " + url;
193237
}
194238

@@ -200,4 +244,46 @@ private List<Future<Integer>> getFutureOfFirst3Number() {
200244
List<Future<Integer>> futures = List.of(Future.of(() -> 1), Future.of(() -> 2), Future.of(() -> 3));
201245
return futures;
202246
}
247+
248+
private static void checkOnSuccessFunction() {
249+
Future<Integer> future = Future.of(() -> 1);
250+
future.onSuccess(i -> System.out.println("Future finish with result: " + i));
251+
}
252+
253+
private static void checkOnFailureFunction() {
254+
Future<Integer> future = Future.of(() -> {throw new RuntimeException("Failed");});
255+
future.onFailure(t -> System.out.println("Future failures with exception: " + t));
256+
}
257+
258+
private static void runAndThenConsumer() {
259+
Future<Integer> future = Future.of(() -> 1);
260+
future.andThen(i -> System.out.println("Do side-effect action 1 with input: " + i.get())).
261+
andThen((i) -> System.out.println("Do side-effect action 2 with input: " + i.get()));
262+
}
263+
264+
public static void main(String[] args) throws InterruptedException {
265+
checkOnSuccessFunction();
266+
checkOnFailureFunction();
267+
runAndThenConsumer();
268+
Thread.sleep(1000);
269+
}
270+
}
271+
272+
273+
class MockConsumer implements Consumer<Integer> {
274+
@Override
275+
public void accept(Integer t) {
276+
}
277+
}
278+
279+
class MockTryConsumer implements Consumer<Try<Integer>> {
280+
@Override
281+
public void accept(Try<Integer> t) {
282+
}
283+
}
284+
285+
class MockThrowableConsumer implements Consumer<Throwable> {
286+
@Override
287+
public void accept(Throwable t) {
288+
}
203289
}

0 commit comments

Comments
 (0)