Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save msievers/6046820d7d56d765b9b3c26310e352ba to your computer and use it in GitHub Desktop.
Save msievers/6046820d7d56d765b9b3c26310e352ba to your computer and use it in GitHub Desktop.
[Spring] Make Async annotated methods run synchronously within (integration) tests

Motivation

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.

Idea

Replace the default TaskExecutor with an instance of SyncTaskExecutor to ensure, that everything runs on the same thread.

Usage

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()
        }
    }
}

Resources

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment