英文:
Spring Boot Integration Testing with TestContainers with MySql - BeanDefinitionStoreException
问题
I'm trying to implement an integration test using TestContainers. But I'm continuously getting BeanDefinitionStoreException. My Test Class:
@SpringBootTest
@AutoConfigureMockMvc
class OrderServiceApplicationTests {
    @Container
    static final MySQLContainer mySQLContainer = new MySQLContainer<>("mysql:8.0.30")
            .withDatabaseName("testcontainer")
            .withUsername("test")
            .withPassword("test");
    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    private MockMvc mockMvc;
    @Autowired
    OrderRepository orderRepository;
    @DynamicPropertySource
    static void setProperties(DynamicPropertyRegistry properties){
        properties.add("spring.datasource.url", mySQLContainer::getJdbcUrl);
        properties.add("spring.datasource.username", mySQLContainer::getUsername);
        properties.add("spring.datasource.password", mySQLContainer::getPassword);
    }
    @Test
    void shouldPlaceOrder() throws Exception {
        OrderItemsDto orderItemsDto = OrderItemsDto.builder()
                .skuCode("Test SKU")
                .price(new BigDecimal(123.32))
                .quantity(2).build();
        OrderDto orderDto = OrderDto.builder()
                .orderItemsDtos(Arrays.asList(orderItemsDto)).build();
        String reqString = objectMapper.writeValueAsString(orderDto);
        mockMvc.perform(MockMvcRequestBuilders.post("api/order")
        .contentType(MediaType.APPLICATION_JSON)
        .content(reqString))
                .andExpect(status().isCreated());
        Assertions.assertTrue(orderRepository.findAll().size() == 1);
    }
}
Here is my POM File:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.1.0-SNAPSHOT</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>order-service</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>order-service</name>
	<description>Order Service</description>
	<properties>
		<java.version>17</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>com.mysql</groupId>
			<artifactId>mysql-connector-j</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.testcontainers</groupId>
			<artifactId>mysql</artifactId>
			<scope>test</scope>
		</dependency>
        <dependency>
            <groupId>org.testcontainers</groupId>
            <artifactId>junit-jupiter</artifactId>
            <scope>test</scope>
        </dependency>
	</dependencies>
	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.testcontainers</groupId>
				<artifactId>testcontainers-bom</artifactId>
				<version>1.18.0</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<repositories>
		<
<details>
<summary>英文:</summary>
I'm trying to implement an integration test using TestContainers. But I'm continuously getting BeanDefinitionStoreException.
My Test Class
    	@SpringBootTest
	@AutoConfigureMockMvc
	class OrderServiceApplicationTests {
		@Container
		static final MySQLContainer mySQLContainer = new MySQLContainer<>("mysql:8.0.30")
				.withDatabaseName("testcontainer")
				.withUsername("test")
				.withPassword("test");
		@Autowired
		ObjectMapper objectMapper;
		@Autowired
		private MockMvc mockMvc;
		@Autowired
		OrderRepository orderRepository;
		@DynamicPropertySource
		static void setProperties(DynamicPropertyRegistry properties){
			properties.add("spring.datasource.url", mySQLContainer::getJdbcUrl);
			properties.add("spring.datasource.username", mySQLContainer::getUsername);
			properties.add("spring.datasource.password", mySQLContainer::getPassword);
		}
		@Test
		void shouldPlaceOrder() throws Exception {
			OrderItemsDto orderItemsDto = OrderItemsDto.builder()
					.skuCode("Test SKU")
					.price(new BigDecimal(123.32))
					.quantity(2).build();
			OrderDto orderDto = OrderDto.builder()
					.orderItemsDtos(Arrays.asList(orderItemsDto)).build();
			String reqString = objectMapper.writeValueAsString(orderDto);
			mockMvc.perform(MockMvcRequestBuilders.post("api/order")
			.contentType(MediaType.APPLICATION_JSON)
			.content(reqString))
					.andExpect(status().isCreated());
			Assertions.assertTrue(orderRepository.findAll().size() == 1);
		}
	}
Here is my POM File
        <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    	<modelVersion>4.0.0</modelVersion>
    	<parent>
    		<groupId>org.springframework.boot</groupId>
    		<artifactId>spring-boot-starter-parent</artifactId>
    		<version>3.1.0-SNAPSHOT</version>
    		<relativePath/> <!-- lookup parent from repository -->
    	</parent>
    	<groupId>com.example</groupId>
    	<artifactId>order-service</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    	<name>order-service</name>
    	<description>Order Service</description>
    	<properties>
    		<java.version>17</java.version>
    	</properties>
    	<dependencies>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-data-jpa</artifactId>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-web</artifactId>
    		</dependency>
    
    		<dependency>
    			<groupId>com.mysql</groupId>
    			<artifactId>mysql-connector-j</artifactId>
    			<scope>runtime</scope>
    		</dependency>
    		<dependency>
    			<groupId>org.projectlombok</groupId>
    			<artifactId>lombok</artifactId>
    			<optional>true</optional>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-test</artifactId>
    			<scope>test</scope>
    		</dependency>
    		<dependency>
    			<groupId>org.testcontainers</groupId>
    			<artifactId>mysql</artifactId>
    			<scope>test</scope>
    		</dependency>
            <dependency>
                <groupId>org.testcontainers</groupId>
                <artifactId>junit-jupiter</artifactId>
                <scope>test</scope>
            </dependency>
    	</dependencies>
    
    	<dependencyManagement>
    		<dependencies>
    			<dependency>
    				<groupId>org.testcontainers</groupId>
    				<artifactId>testcontainers-bom</artifactId>
    				<version>1.18.0</version>
    				<type>pom</type>
    				<scope>import</scope>
    			</dependency>
    		</dependencies>
    	</dependencyManagement>
    
    	<build>
    		<plugins>
    			<plugin>
    				<groupId>org.springframework.boot</groupId>
    				<artifactId>spring-boot-maven-plugin</artifactId>
    				<configuration>
    					<excludes>
    						<exclude>
    							<groupId>org.projectlombok</groupId>
    							<artifactId>lombok</artifactId>
    						</exclude>
    					</excludes>
    				</configuration>
    			</plugin>
    		</plugins>
    	</build>
    	<repositories>
    		<repository>
    			<id>spring-milestones</id>
    			<name>Spring Milestones</name>
    			<url>https://repo.spring.io/milestone</url>
    			<snapshots>
    				<enabled>false</enabled>
    			</snapshots>
    		</repository>
    		<repository>
    			<id>spring-snapshots</id>
    			<name>Spring Snapshots</name>
    			<url>https://repo.spring.io/snapshot</url>
    			<releases>
    				<enabled>false</enabled>
    			</releases>
    		</repository>
    	</repositories>
    	<pluginRepositories>
    		<pluginRepository>
    			<id>spring-milestones</id>
    			<name>Spring Milestones</name>
    			<url>https://repo.spring.io/milestone</url>
    			<snapshots>
    				<enabled>false</enabled>
    			</snapshots>
    		</pluginRepository>
    		<pluginRepository>
    			<id>spring-snapshots</id>
    			<name>Spring Snapshots</name>
    			<url>https://repo.spring.io/snapshot</url>
    			<releases>
    				<enabled>false</enabled>
    			</releases>
    		</pluginRepository>
    	</pluginRepositories>
    
    </project>
This is my console.
    16:14:14.843 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils -- Could not detect default configuration classes for test class [com.example.orderservice.OrderServiceApplicationTests]: OrderServiceApplicationTests does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
    16:14:14.940 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper -- Found @SpringBootConfiguration com.example.orderservice.OrderServiceApplication for test class com.example.orderservice.OrderServiceApplicationTests
    16:14:15.163 [main] WARN org.testcontainers.utility.TestcontainersConfiguration -- Attempted to read Testcontainers configuration file at file:/C:/Users/binul/.testcontainers.properties but the file was not found. Exception message: FileNotFoundException: C:\Users\binul\.testcontainers.properties (The system cannot find the file specified)
    16:14:15.169 [main] INFO org.testcontainers.utility.ImageNameSubstitutor -- Image name substitution will be performed by: DefaultImageNameSubstitutor (composite of 'ConfigurationFileImageNameSubstitutor' and 'PrefixingImageNameSubstitutor')
    
      .   ____          _            __ _ _
     /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
    ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
     \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
      '  |____| .__|_| |_|_| |_\__, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: Spring Boot ::       (v3.1.0-SNAPSHOT)
    
    2023-05-10T16:14:15.441+05:30  INFO 13040 --- [           main] c.e.o.OrderServiceApplicationTests       : Starting OrderServiceApplicationTests using Java 17.0.7 with PID 13040 (started by binul in D:\Project Docs\R&D\Microservices-Online-Shop\order-service)
    2023-05-10T16:14:15.444+05:30  INFO 13040 --- [           main] c.e.o.OrderServiceApplicationTests       : No active profile set, falling back to 1 default profile: "default"
    2023-05-10T16:14:16.013+05:30  INFO 13040 --- [           main] .t.d.DockerMachineClientProviderStrategy : docker-machine executable was not found on PATH ([C:\Program Files\Common Files\Oracle\Java\javapath, C:\Program Files (x86)\Common Files\Oracle\Java\javapath, C:\Windows\system32, C:\Windows, C:\Windows\System32\Wbem, C:\Windows\System32\WindowsPowerShell\v1.0\, C:\Windows\System32\OpenSSH\, C:\Program Files\Git\cmd, C:\Program Files\Java\jdk1.8.0_311\bin, C:\dev_tools\apache-maven-3.8.3\bin, C:\Program Files\PuTTY\, C:\Program Files\dotnet\, C:\Program Files\nodejs\, C:\Program Files\Meld\, C:\Users\binul\AppData\Local\Microsoft\WindowsApps, C:\Users\binul\AppData\Local\Programs\Microsoft VS Code\bin, C:\dev_tools\gradle-6.8.1\bin, C:\Users\binul\AppData\Roaming\npm, C:\Users\binul\.dotnet\tools])
    2023-05-10T16:14:16.014+05:30 ERROR 13040 --- [           main] o.t.d.DockerClientProviderStrategy       : Could not find a valid Docker environment. Please check configuration. Attempted configurations were:
    As no valid configuration was found, execution cannot continue.
    See https://www.testcontainers.org/on_failure.html for more details.
    2023-05-10T16:14:16.027+05:30  WARN 13040 --- [           main] o.s.w.c.s.GenericWebApplicationContext   : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [com.example.orderservice.OrderServiceApplication]: Error processing condition on org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$EmbeddedDatabaseConfiguration
    2023-05-10T16:14:16.054+05:30  INFO 13040 --- [           main] .s.b.a.l.ConditionEvaluationReportLogger : 
    
    Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
    2023-05-10T16:14:16.088+05:30 ERROR 13040 --- [           main] o.s.boot.SpringApplication               : Application run failed
    
    org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [com.example.orderservice.OrderServiceApplication]: Error processing condition on org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$EmbeddedDatabaseConfiguration
    	at org.springframework.context.annotation.ConfigurationClassParser.processImports(ConfigurationClassParser.java:524) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    	at org.springframework.context.annotation.ConfigurationClassParser$DeferredImportSelectorGroupingHandler.lambda$processGroupImports$1(ConfigurationClassParser.java:726) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    	at java.base/java.lang.Iterable.forEach(Iterable.java:75) ~[na:na]
    	at org.springframework.context.annotation.ConfigurationClassParser$DeferredImportSelectorGroupingHandler.processGroupImports(ConfigurationClassParser.java:723) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    	at org.springframework.context.annotation.ConfigurationClassParser$DeferredImportSelectorHandler.process(ConfigurationClassParser.java:694) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    	at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:182) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    	at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:415) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    	at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:287) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    	at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:344) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    	at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:115) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    	at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:747) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:565) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:733) ~[spring-boot-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    	at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:435) ~[spring-boot-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    	at org.springframework.boot.SpringApplication.run(SpringApplication.java:311) ~[spring-boot-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    	at org.springframework.boot.test.context.SpringBootContextLoader.lambda$loadContext$3(SpringBootContextLoader.java:137) ~[spring-boot-test-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    	at org.springframework.util.function.ThrowingSupplier.get(ThrowingSupplier.java:58) ~[spring-core-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    	at org.springframework.util.function.ThrowingSupplier.get(ThrowingSupplier.java:46) ~[spring-core-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    	at org.springframework.boot.SpringApplication.withHook(SpringApplication.java:1405) ~[spring-boot-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    	at org.springframework.boot.test.context.SpringBootContextLoader$ContextLoaderHook.run(SpringBootContextLoader.java:545) ~[spring-boot-test-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    	at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:137) ~[spring-boot-test-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    	at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:108) ~[spring-boot-test-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    	at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:184) ~[spring-test-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    	at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:118) ~[spring-test-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    	at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:127) ~[spring-test-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    	at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:191) ~[spring-test-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    	at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:130) ~[spring-test-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    	at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:241) ~[spring-test-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    	at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:138) ~[spring-test-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    	at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$10(ClassBasedTestDescriptor.java:377) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    	at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.executeAndMaskThrowable(ClassBasedTestDescriptor.java:382) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    	at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$11(ClassBasedTestDescriptor.java:377) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    	at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197) ~[na:na]
    	at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:179) ~[na:na]
    	at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1625) ~[na:na]
    	at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509) ~[na:na]
    	at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499) ~[na:na]
    	at java.base/java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:310) ~[na:na]
    	at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:735) ~[na:na]
    	at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:734) ~[na:na]
    	at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:762) ~[na:na]
    	at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestInstancePostProcessors(ClassBasedTestDescriptor.java:376) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    	at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$instantiateAndPostProcessTestInstance$6(ClassBasedTestDescriptor.java:289) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    	at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateAndPostProcessTestInstance(ClassBasedTestDescriptor.java:288) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    	at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$4(ClassBasedTestDescriptor.java:278) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    	at java.base/java.util.Optional.orElseGet(Optional.java:364) ~[na:na]
    	at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$5(ClassBasedTestDescriptor.java:277) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    	at org.junit.jupiter.engine.execution.TestInstancesProvider.getTestInstances(TestInstancesProvider.java:31) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$prepare$0(TestMethodTestDescriptor.java:105) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:104) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:68) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$2(NodeTestTask.java:123) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    	at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:123) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    	at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:90) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    	at java.base/java.util.ArrayList.forEach(ArrayList.java:1511) ~[na:na]
    	at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    	at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    	at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    	at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    	at java.base/java.util.ArrayList.forEach(ArrayList.java:1511) ~[na:na]
    	at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    	at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    	at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    	at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    	at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    	at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:147) ~[junit-platform-launcher-1.9.3.jar:1.9.3]
    	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:127) ~[junit-platform-launcher-1.9.3.jar:1.9.3]
    	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:90) ~[junit-platform-launcher-1.9.3.jar:1.9.3]
    	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:55) ~[junit-platform-launcher-1.9.3.jar:1.9.3]
    	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:102) ~[junit-platform-launcher-1.9.3.jar:1.9.3]
    	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:54) ~[junit-platform-launcher-1.9.3.jar:1.9.3]
    	at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114) ~[junit-platform-launcher-1.9.3.jar:1.9.3]
    	at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86) ~[junit-platform-launcher-1.9.3.jar:1.9.3]
    	at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86) ~[junit-platform-launcher-1.9.3.jar:1.9.3]
    	at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53) ~[junit-platform-launcher-1.9.3.jar:1.9.3]
    	at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69) ~[junit5-rt.jar:na]
    	at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) ~[junit-rt.jar:na]
    	at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) ~[junit-rt.jar:na]
    	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) ~[junit-rt.jar:na]
    Caused by: java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$EmbeddedDatabaseConfiguration
    	at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:60) ~[spring-boot-autoconfigure-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    	at org.springframework.context.annotation.ConditionEvaluator.shouldSkip(ConditionEvaluator.java:108) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    	at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:219) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    	at org.springframework.context.annotation.ConfigurationClassParser.processMemberClasses(ConfigurationClassParser.java:365) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    	at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:265) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    	at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:243) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    	at org.springframework.context.annotation.ConfigurationClassParser.processImports(ConfigurationClassParser.java:514) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    	... 93 common frames omitted
    Caused by: java.lang.IllegalStateException: Previous attempts to find a Docker environment failed. Will not retry. Please see logs and check configuration
    	at org.testcontainers.dockerclient.DockerClientProviderStrategy.getFirstValidStrategy(DockerClientProviderStrategy.java:212) ~[testcontainers-1.18.0.jar:1.18.0]
    	at org.testcontainers.DockerClientFactory.getOrInitializeStrategy(DockerClientFactory.java:150) ~[testcontainers-1.18.0.jar:1.18.0]
    	at org.testcontainers.DockerClientFactory.dockerHostIpAddress(DockerClientFactory.java:323) ~[testcontainers-1.18.0.jar:1.18.0]
    	at org.testcontainers.containers.ContainerState.getHost(ContainerState.java:64) ~[testcontainers-1.18.0.jar:na]
    	at org.testcontainers.containers.MySQLContainer.getJdbcUrl(MySQLContainer.java:104) ~[mysql-1.18.0.jar:na]
    	at com.example.orderservice.OrderServiceApplicationTests.lambda$setProperties$0(OrderServiceApplicationTests.java:46) ~[test-classes/:na]
    	at org.springframework.test.context.support.DynamicValuesPropertySource.getProperty(DynamicValuesPropertySource.java:43) ~[spring-test-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    	at org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:85) ~[spring-core-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    	at org.springframework.boot.context.properties.source.ConfigurationPropertySourcesPropertyResolver$DefaultResolver.getProperty(ConfigurationPropertySourcesPropertyResolver.java:123) ~[spring-boot-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    	at org.springframework.boot.context.properties.source.ConfigurationPropertySourcesPropertyResolver.findPropertyValue(ConfigurationPropertySourcesPropertyResolver.java:97) ~[spring-boot-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    	at org.springframework.boot.context.properties.source.ConfigurationPropertySourcesPropertyResolver.getProperty(ConfigurationPropertySourcesPropertyResolver.java:74) ~[spring-boot-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    	at org.springframework.boot.context.properties.source.ConfigurationPropertySourcesPropertyResolver.getProperty(ConfigurationPropertySourcesPropertyResolver.java:60) ~[spring-boot-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    	at org.springframework.core.env.AbstractEnvironment.getProperty(AbstractEnvironment.java:552) ~[spring-core-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    	at org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$EmbeddedDatabaseCondition.hasDataSourceUrlProperty(DataSourceAutoConfiguration.java:156) ~[spring-boot-autoconfigure-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    	at org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$EmbeddedDatabaseCondition.getMatchOutcome(DataSourceAutoConfiguration.java:139) ~[spring-boot-autoconfigure-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    	at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:47) ~[spring-boot-autoconfigure-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    	... 99 common frames omitted
I highly suspect that this is related to injecting Mysql image into the local environment.
Note : I did the same code to Mongodb and it works fine.
Could anyone had the same issue and resolved ? btw unit testing becoming embarrassing :-( 
</details>
# 答案1
**得分**: 1
我认为你的测试类缺少 `@Testcontainers`。
<details>
<summary>英文:</summary>
I think you are missing `@Testcontainers` over your test class.
</details>
# 答案2
**得分**: 0
请在类级别添加`@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)`。
<details>
<summary>英文:</summary>
Add `@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)` at class level
</details>
# 答案3
**得分**: 0
尝试删除 @Container 注释,并将 mySQLContainer.start() 添加到这个方法中。
```java
@DynamicPropertySource
static void setProperties(DynamicPropertyRegistry properties){
   mySQLContainer.start();
   properties.add("spring.datasource.url", mySQLContainer::getJdbcUrl);
   properties.add("spring.datasource.username", mySQLContainer::getUsername);
   properties.add("spring.datasource.password", mySQLContainer::getPassword);
}
英文:
Try to remove @Container annotation and add mySQLContainer.start() to this method.
@DynamicPropertySource
static void setProperties(DynamicPropertyRegistry properties){
mySQLContainer.start();
properties.add("spring.datasource.url", mySQLContainer::getJdbcUrl);
properties.add("spring.datasource.username", mySQLContainer::getUsername);
properties.add("spring.datasource.password", mySQLContainer::getPassword);
}
答案4
得分: 0
根据您提供的堆栈最后一部分,您未提供在PATH上运行并可用的有效Docker安装。
我建议您通过官方方式确保Docker Desktop的安装:https://docs.docker.com/engine/install/
之后,并且如前面所述使用@Testcontainers应该有助于您在测试过程中进一步。
英文:
Based on the final portion of the stack you are not providing a valid Docker installation running and available at your PATH.
I would recommend you to ensure the Docker Desktop installation via official ways at: https://docs.docker.com/engine/install/
After that and using the @Testcontainers as stated before should help you further in the testing process.
答案5
得分: 0
以下是已翻译的内容:
为了进行测试,请尝试在测试类上添加 @SpringBootTest 和 @Testcontainers。
但就个人而言,我认为您可以更改您的测试策略,以使测试更加有效。
- 测试与数据库相关的功能,如 Repository、XXXTemplate,可以使用 
@DataJdbcTest或其他 DataXXXTest 与 testcontainers 数据库进行测试。 - 模拟 Repository 并使用 
@WebMvcTest或@WebFluxTest等针对 Controller/API 进行测试。 - 使用最新的 Spring 
WebClient在集成环境中使用@SpringBootTest(....RAMDON_PORT)验证功能。 
请查看我的 Spring Boot 示例项目,其中包含测试代码,链接在此处,https://github.com/hantsy/spring6-sandbox/tree/master/boot/src/test/java/com/example/demo
英文:
For your test try to add @SpringBootTest and @Testcontainers on the test class.
But personally I think you could change your testing strategy to make tests more effectively.
- Test the db related features, such as Repository, XXXTemplate with 
@DataJdbcTestor other DataXXXTest with a testcontainers database. - Mock the Repository and test against the Controller/APIs with 
@WebMvcTestor@WebFluxTest, etc - Use the latest Spring 
WebClientto verify the functionality in an integration env with@SpringBootTest(....RAMDON_PORT) 
Check my Spring Boot example project with testing codes here, https://github.com/hantsy/spring6-sandbox/tree/master/boot/src/test/java/com/example/demo
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论