How to disable async operation for specific test cases in Spring Boot

  • |
  • 30 August 2023
Post image

I was facing a challenge with running test cases that include async methods in my Spring Boot application. The test cases failed because the async method didn’t complete before the test case finished. I have discovered that when you remove or disable the async configuration, the test cases pass.

To specifically disable async operation for certain test cases, we can use the SyncTaskExecutor class provided by Spring, which executes tasks synchronously in the calling thread. Here’s how you can set it up:

  1. Create a configuration class in your test folder, let’s name it DisableAsyncConfiguration:
public class DisableAsyncConfiguration {

    @Bean
    public Executor taskExecutor() {
        return new SyncTaskExecutor();
    }
}
  • SyncTaskExecutor is a class which is TaskExecutor implementation that executes each task synchronously in the calling thread.
    • And the best part it is designed for testing scenarios
  1. Import this configuration class in your test class using the @Import annotation. For example:
// import the configuration, from now on async operation will run on SyncTaskExecutor for these test class
@Import(value = {DisableAsyncConfiguration.class})
public class AnyTest {
    @Test
    void testIncludesAsyncCall() throws Exception {
        // ...
    }
}

By importing the DisableAsyncConfiguration class, the async operations in your test class will be executed synchronously using the SyncTaskExecutor, allowing you to properly test them.

You May Also Like