1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 package com.jcabi.aspects;
31
32 import java.util.concurrent.BlockingQueue;
33 import java.util.concurrent.Future;
34 import java.util.concurrent.LinkedBlockingQueue;
35 import java.util.concurrent.TimeUnit;
36 import org.hamcrest.Matcher;
37 import org.hamcrest.MatcherAssert;
38 import org.hamcrest.Matchers;
39 import org.junit.jupiter.api.Assertions;
40 import org.junit.jupiter.api.Test;
41
42
43
44
45
46 final class AsyncTest {
47
48
49
50
51 private static final Matcher<String> THREAD_NAME = Matchers.allOf(
52 Matchers.not(Thread.currentThread().getName()),
53 Matchers.startsWith("jcabi-async")
54 );
55
56 @Test
57 @SuppressWarnings("PMD.DoNotUseThreads")
58 void executesAsynchronously() throws Exception {
59 final BlockingQueue<String> queue = new LinkedBlockingQueue<>();
60 final Runnable runnable = new Runnable() {
61 @Async
62 @Override
63 public void run() {
64 queue.offer(Thread.currentThread().getName());
65 }
66 };
67 runnable.run();
68
69 MatcherAssert.assertThat(
70 queue.poll(30, TimeUnit.SECONDS),
71 AsyncTest.THREAD_NAME
72 );
73 }
74
75 @Test
76 void returnsFutureValue() throws Exception {
77 MatcherAssert.assertThat(
78 new AsyncTest.Foo().asyncMethodWithReturnValue()
79 .get(5, TimeUnit.MINUTES),
80 AsyncTest.THREAD_NAME
81 );
82 }
83
84 @Test
85 void throwsWhenMethodDoesNotReturnVoidOrFuture() {
86 Assertions.assertThrows(
87 IllegalStateException.class,
88 () -> new AsyncTest.Foo().asyncMethodThatReturnsInt()
89 );
90 }
91
92
93
94
95
96 private static final class Foo {
97
98
99
100
101
102 @Async
103 public Future<String> asyncMethodWithReturnValue() {
104
105 return new Future<String>() {
106
107 @Override
108 public boolean cancel(final boolean interruptible) {
109 return false;
110 }
111
112 @Override
113 public boolean isCancelled() {
114 return false;
115 }
116
117 @Override
118 public boolean isDone() {
119 return true;
120 }
121
122 @Override
123 public String get() {
124 return Thread.currentThread().getName();
125 }
126
127 @Override
128 public String get(final long timeout, final TimeUnit unit) {
129 return Thread.currentThread().getName();
130 }
131 };
132 }
133
134
135
136
137
138
139 @Async
140 public int asyncMethodThatReturnsInt() {
141 return 0;
142 }
143 }
144
145 }