CopyPastor

Detecting plagiarism made easy.

Score: 1; Reported for: Exact paragraph match Open both answers

Possible Plagiarism

Reposted on 2025-12-17
by Luca Tampellini

Original Post

Original - Posted on 2025-12-17
by Luca Tampellini



            
Present in both answers; Present only in the new answer; Present only in the old answer;

If you dont want to disable the `@EnableAsync`, you may also leave the `@Async` execution all-together and still let your test wait till the asynchronous processing is finished!
## The idea 1. Inject your `TaskExecutor` 2. Await termination of the task, with a maximum timeout
## The implementation ``` @Autowired ExecutorService taskExecutor;
@Test public void someTest() throws InterruptedException { //... call here your async methods (directly or indirectly) ... final var asyncFinished = taskExecutor.awaitTermination(5, TimeUnit.MINUTES); Assertions.assertTrue(asyncFinished); } ```
## Notes You may need to specialise the injection, depending on the configurations you are using the dependencies that you are adding : use the that you used to instance the executor service in that case, e.g.: `ThreadPoolTaskExecutor`, from which you can access the inner `ExecutorService` with `taskExecutor.getThreadPoolExecutor()`
## No timeout? Alternatively, you may invoke `shutdown` and wait for the threads to finish, without timeout
# What about an alternative to disabling asynchronous execution? I had the same issue, but in my case i wanted to keep *async* execution : to have a proper integration testing, **you may in fact want to have an execution context that is the as similar as possible to the real context** and to the real execution of your spring application!
## The idea 1. Inject your `TaskExecutor` 2. Await termination of the task, with a maximum timeout
## The implementation
``` @Autowired ExecutorService taskExecutor;
@Test public void someTest() throws InterruptedException { //... call here your async methods (directly or indirectly) ... final var asyncFinished = taskExecutor.awaitTermination(5, TimeUnit.MINUTES); Assertions.assertTrue(asyncFinished); } ```
## No timeout? Alternatively, you may invoke `shutdown` and wait for the threads to finish, without timeout

        
Present in both answers; Present only in the new answer; Present only in the old answer;