|
| 1 | +package org.baeldung.async; |
| 2 | + |
| 3 | +import java.util.concurrent.ExecutionException; |
| 4 | +import java.util.concurrent.Future; |
| 5 | + |
| 6 | +import org.baeldung.async.config.SpringAsyncConfig; |
| 7 | +import org.junit.Test; |
| 8 | +import org.junit.runner.RunWith; |
| 9 | +import org.springframework.beans.factory.annotation.Autowired; |
| 10 | +import org.springframework.test.context.ContextConfiguration; |
| 11 | +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; |
| 12 | +import org.springframework.test.context.support.AnnotationConfigContextLoader; |
| 13 | + |
| 14 | +@RunWith(SpringJUnit4ClassRunner.class) |
| 15 | +@ContextConfiguration(classes = { SpringAsyncConfig.class }, loader = AnnotationConfigContextLoader.class) |
| 16 | +public class AsyncAnnotationExampleTest { |
| 17 | + |
| 18 | + @Autowired |
| 19 | + AsyncAnnotationExample asyncAnnotationExample; |
| 20 | + |
| 21 | + @Test |
| 22 | + public void testAsyncAnnotationForMethodsWithVoidReturnType() { |
| 23 | + System.out.println("Start - invoking an asynchronous method. " |
| 24 | + + Thread.currentThread().getName()); |
| 25 | + asyncAnnotationExample.asyncMethodWithVoidReturnType(); |
| 26 | + System.out.println("End - invoking an asynchronous method. "); |
| 27 | + } |
| 28 | + |
| 29 | + @Test |
| 30 | + public void testAsyncAnnotationForMethodsWithReturnType() |
| 31 | + throws InterruptedException, ExecutionException { |
| 32 | + System.out.println("Start - invoking an asynchronous method. " |
| 33 | + + Thread.currentThread().getName()); |
| 34 | + final Future<String> future = asyncAnnotationExample |
| 35 | + .asyncMethodWithReturnType(); |
| 36 | + |
| 37 | + while (true) { |
| 38 | + if (future.isDone()) { |
| 39 | + System.out.println("Result from asynchronous process - " |
| 40 | + + future.get()); |
| 41 | + break; |
| 42 | + } |
| 43 | + System.out.println("Continue doing something else. "); |
| 44 | + Thread.sleep(1000); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + @Test |
| 49 | + public void testAsyncAnnotationForMethodsWithConfiguredExecutor() { |
| 50 | + System.out.println("Start - invoking an asynchronous method. "); |
| 51 | + asyncAnnotationExample.asyncMethodWithConfiguredExecutor(); |
| 52 | + System.out.println("End - invoking an asynchronous method. "); |
| 53 | + } |
| 54 | + |
| 55 | + @Test |
| 56 | + public void testAsyncAnnotationForMethodsWithException() throws Exception { |
| 57 | + System.out.println("Start - invoking an asynchronous method. "); |
| 58 | + asyncAnnotationExample.asyncMethodWithExceptions(); |
| 59 | + System.out.println("End - invoking an asynchronous method. "); |
| 60 | + } |
| 61 | +} |
0 commit comments