I would like to disable @EnableAsync
when I run my integration tests.
I tried to override the configuration file which is annotated with @EnableAsync
with a class with the same name in my test package but it does not work.
In this topic: Is it possible to disable Spring's @Async during integration test?
I have seen that:
You can... Create a test configuration or simply override the task executor with a SyncTaskExecutor
but I do not understand how to do.
Any advice ? Thanks
@SpringBootTest It starts the embedded server, creates a web environment and then enables @Test methods to do integration testing. By default, @SpringBootTest does not start a server. We need to add attribute webEnvironment to further refine how your tests run.
The @SpringBootTest annotation is useful when we need to bootstrap the entire container. The annotation works by creating the ApplicationContext that will be utilized in our tests. We can use the webEnvironment attribute of @SpringBootTest to configure our runtime environment; we're using WebEnvironment.
Spring Boot provides a @SpringBootTest annotation, which can be used as an alternative to the standard spring-test @ContextConfiguration annotation when you need Spring Boot features. The annotation works by creating the ApplicationContext used in your tests through SpringApplication .
The @EnableAsync annotation switches on Spring's ability to run @Async methods in a background thread pool. This class also customizes the Executor by defining a new bean. Here, the method is named taskExecutor , since this is the specific method name for which Spring searches.
The topic you linked does offer a good solution.
To create a SyncTaskExecutor
for tests, make sure you actually have a test configuration class for spring context. Please, refer to Spring docs for that:
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html
In this configuration class add a new bean:
@Bean
@Primary
public TaskExecutor taskExecutor() {
return new SyncTaskExecutor();
}
That should do it!
Take care not to create this bean in your live config!
If a unique profile name is used when the tests are run (e.g. "test"), then the easiest way to disable async when running tests is with
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.EnableAsync;
@Profile("!test")
@Configuration
@EnableAsync
public class AsyncConfiguration {
}
In my case I had to add the following to src/test/resources/application.yml
to ensure tests are run under a profile named "test"
spring:
profiles:
active: test
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With