1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.lang3.concurrent;
18
19 import static org.junit.jupiter.api.Assertions.assertEquals;
20 import static org.junit.jupiter.api.Assertions.assertThrows;
21
22 import java.util.concurrent.Callable;
23 import java.util.concurrent.ExecutorService;
24 import java.util.concurrent.Executors;
25 import java.util.concurrent.TimeUnit;
26
27 import org.apache.commons.lang3.AbstractLangTest;
28 import org.junit.jupiter.api.Test;
29
30
31
32
33 public class CallableBackgroundInitializerTest extends AbstractLangTest {
34
35
36
37
38 private static final class TestCallable implements Callable<Integer> {
39
40 int callCount;
41
42
43
44
45 @Override
46 public Integer call() {
47 callCount++;
48 return RESULT;
49 }
50 }
51
52
53 private static final Integer RESULT = Integer.valueOf(42);
54
55
56
57
58
59 @Test
60 public void testInitExecutor() throws InterruptedException {
61 final ExecutorService exec = Executors.newSingleThreadExecutor();
62 final CallableBackgroundInitializer<Integer> init = new CallableBackgroundInitializer<>(
63 new TestCallable(), exec);
64 assertEquals(exec, init.getExternalExecutor(), "Executor not set");
65 exec.shutdown();
66 exec.awaitTermination(1, TimeUnit.SECONDS);
67 }
68
69
70
71
72
73 @Test
74 public void testInitExecutorNullCallable() throws InterruptedException {
75 final ExecutorService exec = Executors.newSingleThreadExecutor();
76 try {
77 assertThrows(NullPointerException.class, () -> new CallableBackgroundInitializer<Integer>(null, exec));
78 } finally {
79 exec.shutdown();
80 exec.awaitTermination(1, TimeUnit.SECONDS);
81 }
82
83 }
84
85
86
87
88
89
90 @Test
91 public void testInitialize() throws Exception {
92 final TestCallable call = new TestCallable();
93 final CallableBackgroundInitializer<Integer> init = new CallableBackgroundInitializer<>(
94 call);
95 assertEquals(RESULT, init.initialize(), "Wrong result");
96 assertEquals(1, call.callCount, "Wrong number of invocations");
97 }
98
99
100
101
102
103 @Test()
104 public void testInitNullCallable() {
105 assertThrows(NullPointerException.class, () -> new CallableBackgroundInitializer<>(null));
106 }
107 }