If you are writing (integration) tests and you want to debug code within the scope of a method annotated with @Async
(e.g. an event handler) your IDE might skip over breakpoints within the async code because it might be executed on a
different/new thread.
Replace the default TaskExecutor
with an instance of SyncTaskExecutor
to ensure, that everything runs on the same thread.
The following is an example for a spring boot integration test using spock/spring boot 2. See the Spring Boot docs for an in-depth
explanation of @TestConfiguration
. The key aspect is, that if you want to customize the primary configuration, you can use a nested @TestConfiguration class.
@SpringBootTest
class SomeIntegrationSpec extends Specification {
@TestConfiguration
static class TaskExecutorTestConfiguration {
/**
* In order to ease testing of async event handlers we overwrite Springs default TaskExecutor
* with an in-thread version. Each invocation takes place in the calling thread.
*
* @return an instance of SyncTaskExecutor
*/
@Bean TaskExecutor taskExecutor() {
return new SyncTaskExecutor()
}
}
}