英文:
java.lang.IllegalStateException: Failed to load ApplicationContext for JUnit 5 Testing with H2 in Memory Database
问题
I am currently trying to test my repositories with JUnit and Assertj. This is my test folder structure:
Here is my entire application folder structure:
Also all the folders are marked correctly.
This is my application.properties in which I try to configure an in-memory H2 database:
# Datasource Settings
spring.datasource.url=jdbc:h2:mem:test;DB_CLOSE_DELAY=-1
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=sa
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
# Hibernate Settings
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.show_sql=false
# H2 Console Settings
spring.h2.console.enabled=true
spring.h2.console.path=/h2
And finally this is my test class to test LehrerRepository.java
package de.gabriel.vertretungsplan.repositories;
import de.gabriel.vertretungsplan.models.enums.Anwesenheit;
import de.gabriel.vertretungsplan.models.enums.Rolle;
import de.gabriel.vertretungsplan.models.users.Lehrer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.ActiveProfiles;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
@ActiveProfiles("test")
@DataJpaTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class LehrerRepositoryTest {
@Autowired
private LehrerRepository lehrerRepository;
@BeforeAll
void init() {
lehrerRepository.saveAllAndFlush(List.of(
new Lehrer("chemielehrer", "chemielehrer", Rolle.getPrefixedRolle(Rolle.LEHRER), Anwesenheit.ANWESEND),
new Lehrer("mathematiklehrer", "mathematiklehrer", Rolle.getPrefixedRolle(Rolle.LEHRER), Anwesenheit.ABWESEND)
));
}
@AfterAll
void tearDown() {
lehrerRepository.deleteAll();
}
@Test
void findByAnwesenheit() {
List<Lehrer> anwesend = lehrerRepository.findByAnwesenheit(Anwesenheit.ANWESEND);
List<Lehrer> abwesend = lehrerRepository.findByAnwesenheit(Anwesenheit.ABWESEND);
assertThat(anwesend).isNotNull();
assertThat(abwesend).isNotNull();
assertThat(anwesend.get(0).getUsername()).isEqualTo("chemielehrer");
assertThat(abwesend.get(0).getUsername()).isEqualTo("mathematiklehrer");
}
@Test
void findByName() {
Optional<Lehrer> chemielehrer = lehrerRepository.findByName("chemielehrer");
assertThat(chemielehrer).isNotEmpty();
assertThat(chemielehrer.get().getUsername()).isEqualTo("chemielehrer");
}
}
This is part of the error log (where the error occurs):
java.lang.IllegalStateException: Failed to load ApplicationContext for [MergedContextConfiguration@35ff8fc9 testClass = de.gabriel.vertretungsplan.repositories.LehrerRepositoryTest, locations = [], classes = [de.gabriel.vertretungsplan.VertretungsplanApplication], contextInitializerClasses = [], activeProfiles = ["test"], propertySourceLocations = [], propertySourceProperties = ["org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper=true"], contextCustomizers = [[ImportsContextCustomizer@5fb7183b key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.sql.init.SqlInitializationAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@359df09a, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@792b749c, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@66982506, org.springframework.boot.test.autoconfigure.actuate.observability.ObservabilityContextCustomizerFactory$DisableObservabilityContextCustomizer@9da1, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@dddf414e, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@30f842ca, org.springframework.boot.test.context.SpringBootTestAnnotation@b55a11a], contextLoader = org.springframework.boot.test.context.SpringBootContextLoader, parent = null]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:141)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:127)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:141)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:97)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:249)
at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:138)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$10(ClassBasedTestDescriptor.java:377)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.executeAndMaskThrowable(ClassBasedTestDescriptor.java:382)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$11(ClassBasedTestDescriptor.java:377)
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197)
at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:179)
at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1625)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)
at java.base/java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:310)
at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java
<details>
<summary>英文:</summary>
I am currently trying to test my repositories with JUnit and Assertj. This is my test folder structure:
[![][1]][1]
Here is my entire application folder structure:
[![][2]][2]
Also all the folders are marked correctly.
[![][3]][3]
This is my **application.properties** in which I try to configure a in memory h2 db:
Datasource Settings
spring.datasource.url=jdbc:h2:mem:test;DB_CLOSE_DELAY=-1
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=sa
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
Hibernate Settings
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.show_sql=false
H2 Console Settings
spring.h2.console.enabled=true
spring.h2.console.path=/h2
And finally this is my test class to test **LehrerRepository.java**
```java
package de.gabriel.vertretungsplan.repositories;
import de.gabriel.vertretungsplan.models.enums.Anwesenheit;
import de.gabriel.vertretungsplan.models.enums.Rolle;
import de.gabriel.vertretungsplan.models.users.Lehrer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.ActiveProfiles;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
@ActiveProfiles("test")
@DataJpaTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class LehrerRepositoryTest {
@Autowired
private LehrerRepository lehrerRepository;
@BeforeAll
void init() {
lehrerRepository.saveAllAndFlush(List.of(
new Lehrer("chemielehrer", "chemielehrer", Rolle.getPrefixedRolle(Rolle.LEHRER), Anwesenheit.ANWESEND),
new Lehrer("mathematiklehrer", "mathematiklehrer", Rolle.getPrefixedRolle(Rolle.LEHRER), Anwesenheit.ABWESEND)
));
}
@AfterAll
void tearDown() {
lehrerRepository.deleteAll();
}
@Test
void findByAnwesenheit() {
List<Lehrer> anwesend = lehrerRepository.findByAnwesenheit(Anwesenheit.ANWESEND);
List<Lehrer> abwesend = lehrerRepository.findByAnwesenheit(Anwesenheit.ABWESEND);
assertThat(anwesend).isNotNull();
assertThat(abwesend).isNotNull();
assertThat(anwesend.get(0).getUsername()).isEqualTo("chemielehrer");
assertThat(abwesend.get(0).getUsername()).isEqualTo("mathematiklehrer");
}
@Test
void findByName() {
Optional<Lehrer> chemielehrer = lehrerRepository.findByName("chemielehrer");
assertThat(chemielehrer).isNotEmpty();
assertThat(chemielehrer.get().getUsername()).isEqualTo("chemielehrer");
}
}
This is part of the error log (where the error occurs):
java.lang.IllegalStateException: Failed to load ApplicationContext for [MergedContextConfiguration@35ff8fc9 testClass = de.gabriel.vertretungsplan.repositories.LehrerRepositoryTest, locations = [], classes = [de.gabriel.vertretungsplan.VertretungsplanApplication], contextInitializerClasses = [], activeProfiles = ["test"], propertySourceLocations = [], propertySourceProperties = ["org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper=true"], contextCustomizers = [[ImportsContextCustomizer@5fb7183b key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.sql.init.SqlInitializationAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@359df09a, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@792b749c, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@66982506, org.springframework.boot.test.autoconfigure.actuate.observability.ObservabilityContextCustomizerFactory$DisableObservabilityContextCustomizer@9da1, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@dddf414e, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@30f842ca, org.springframework.boot.test.context.SpringBootTestAnnotation@b55a11a], contextLoader = org.springframework.boot.test.context.SpringBootContextLoader, parent = null]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:141)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:127)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:141)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:97)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:249)
at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:138)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$10(ClassBasedTestDescriptor.java:377)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.executeAndMaskThrowable(ClassBasedTestDescriptor.java:382)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$11(ClassBasedTestDescriptor.java:377)
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197)
at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:179)
at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1625)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)
at java.base/java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:310)
at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:735)
at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:762)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestInstancePostProcessors(ClassBasedTestDescriptor.java:376)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$instantiateAndPostProcessTestInstance$6(ClassBasedTestDescriptor.java:289)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateAndPostProcessTestInstance(ClassBasedTestDescriptor.java:288)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$4(ClassBasedTestDescriptor.java:278)
at java.base/java.util.Optional.orElseGet(Optional.java:364)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$5(ClassBasedTestDescriptor.java:277)
at org.junit.jupiter.engine.execution.TestInstancesProvider.getTestInstances(TestInstancesProvider.java:31)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$before$2(ClassBasedTestDescriptor.java:203)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.before(ClassBasedTestDescriptor.java:202)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.before(ClassBasedTestDescriptor.java:84)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:148)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:147)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:127)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:90)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:55)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:102)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:54)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:57)
at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Caused by: java.lang.IllegalStateException: Unable to retrieve @EnableAutoConfiguration base packages
at org.springframework.boot.autoconfigure.AutoConfigurationPackages.get(AutoConfigurationPackages.java:78)
at org.springframework.boot.autoconfigure.data.AbstractRepositoryConfigurationSourceSupport.getBasePackages(AbstractRepositoryConfigurationSourceSupport.java:79)
at org.springframework.boot.autoconfigure.data.AbstractRepositoryConfigurationSourceSupport$AutoConfiguredAnnotationRepositoryConfigurationSource.getBasePackages(AbstractRepositoryConfigurationSourceSupport.java:138)
at org.springframework.data.repository.config.RepositoryConfigurationSourceSupport.lambda$getCandidates$1(RepositoryConfigurationSourceSupport.java:75)
at org.springframework.data.util.LazyStreamable.stream(LazyStreamable.java:47)
at org.springframework.data.util.LazyStreamable.iterator(LazyStreamable.java:42)
at org.springframework.data.repository.config.RepositoryConfigurationExtensionSupport.getRepositoryConfigurations(RepositoryConfigurationExtensionSupport.java:80)
at org.springframework.data.repository.config.RepositoryConfigurationDelegate.registerRepositoriesIn(RepositoryConfigurationDelegate.java:163)
at org.springframework.boot.autoconfigure.data.AbstractRepositoryConfigurationSourceSupport.registerBeanDefinitions(AbstractRepositoryConfigurationSourceSupport.java:62)
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.lambda$loadBeanDefinitionsFromRegistrars$1(ConfigurationClassBeanDefinitionReader.java:373)
at java.base/java.util.LinkedHashMap.forEach(LinkedHashMap.java:721)
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsFromRegistrars(ConfigurationClassBeanDefinitionReader.java:372)
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:148)
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:120)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:409)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:283)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:344)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:115)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:745)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:565)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:432)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:308)
at org.springframework.boot.test.context.SpringBootContextLoader.lambda$loadContext$3(SpringBootContextLoader.java:137)
at org.springframework.util.function.ThrowingSupplier.get(ThrowingSupplier.java:59)
at org.springframework.util.function.ThrowingSupplier.get(ThrowingSupplier.java:47)
at org.springframework.boot.SpringApplication.withHook(SpringApplication.java:1386)
at org.springframework.boot.test.context.SpringBootContextLoader$ContextLoaderHook.run(SpringBootContextLoader.java:543)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:137)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:108)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:183)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
... 65 more
I can see that is has problems finding some Application Context, but in the tutorial I watched there is no mention of another config class.
What I have tried
-
I read this article: https://www.baeldung.com/spring-junit-failed-to-load-applicationcontext but I don't have any of these files "you need" to reproduce the error
-
I tried what a comment from this post suggested: https://stackoverflow.com/questions/75337854/failed-to-load-applicationcontext-spring-boot-repository, but I already set the scope for tests in my pom.xml
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.24.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.9.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>5.2.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.1.214</version>
<scope>test</scope>
</dependency>
- I tried the @SpringBootTest annotation but this just gives me a new error
java.lang.IllegalStateException: Configuration error: found multiple declarations of @BootstrapWith for test class [de.gabriel.vertretungsplan.repositories.LehrerRepositoryTest]: [@org.springframework.test.context.BootstrapWith(value=org.springframework.boot.test.context.SpringBootTestContextBootstrapper.class), @org.springframework.test.context.BootstrapWith(value=org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper.class)]
at org.springframework.test.context.BootstrapUtils.resolveExplicitTestContextBootstrapper(BootstrapUtils.java:194)
at org.springframework.test.context.BootstrapUtils.resolveTestContextBootstrapper(BootstrapUtils.java:150)
at org.springframework.test.context.BootstrapUtils.resolveTestContextBootstrapper(BootstrapUtils.java:126)
at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:122)
at org.junit.jupiter.engine.execution.ExtensionValuesStore.lambda$getOrComputeIfAbsent$4(ExtensionValuesStore.java:86)
at org.junit.jupiter.engine.execution.ExtensionValuesStore$MemoizingSupplier.computeValue(ExtensionValuesStore.java:223)
at org.junit.jupiter.engine.execution.ExtensionValuesStore$MemoizingSupplier.get(ExtensionValuesStore.java:211)
at org.junit.jupiter.engine.execution.ExtensionValuesStore$StoredValue.evaluate(ExtensionValuesStore.java:191)
at org.junit.jupiter.engine.execution.ExtensionValuesStore$StoredValue.access$100(ExtensionValuesStore.java:171)
at org.junit.jupiter.engine.execution.ExtensionValuesStore.getOrComputeIfAbsent(ExtensionValuesStore.java:89)
at org.junit.jupiter.engine.execution.ExtensionValuesStore.getOrComputeIfAbsent(ExtensionValuesStore.java:93)
at org.junit.jupiter.engine.execution.NamespaceAwareStore.getOrComputeIfAbsent(NamespaceAwareStore.java:61)
at org.springframework.test.context.junit.jupiter.SpringExtension.getTestContextManager(SpringExtension.java:294)
at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:138)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$10(ClassBasedTestDescriptor.java:377)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.executeAndMaskThrowable(ClassBasedTestDescriptor.java:382)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$11(ClassBasedTestDescriptor.java:377)
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197)
at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:179)
at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1625)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)
at java.base/java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:310)
at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:735)
at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:762)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestInstancePostProcessors(ClassBasedTestDescriptor.java:376)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$instantiateAndPostProcessTestInstance$6(ClassBasedTestDescriptor.java:289)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateAndPostProcessTestInstance(ClassBasedTestDescriptor.java:288)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$4(ClassBasedTestDescriptor.java:278)
at java.base/java.util.Optional.orElseGet(Optional.java:364)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$5(ClassBasedTestDescriptor.java:277)
at org.junit.jupiter.engine.execution.TestInstancesProvider.getTestInstances(TestInstancesProvider.java:31)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$before$2(ClassBasedTestDescriptor.java:203)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.before(ClassBasedTestDescriptor.java:202)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.before(ClassBasedTestDescriptor.java:84)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:148)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:147)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:127)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:90)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:55)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:102)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:54)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:57)
at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
- Renaming application.properties to application-test.properties and configuring test as the active profile:
spring.config.activate.on-profile=test
- I also tried some annotations suggested to me in the comments:
@EntityScan(basePackages = "de.gabriel.vertretungsplan.models")
@EnableJpaRepositories(basePackages = "de.gabriel.vertretungsplan.repositories")
Using the first annotation, @EntityScan, I get: java.lang.IllegalStateException: Failed to load ApplicationContext for
And using the second annotation @EnableJpaRepositories, I get:
org.springframework.dao.InvalidDataAccessResourceUsageException: could not prepare statement
- Making a class with the @SpringBootTest annotation to see if the application context gets loaded there. This text (
contextLoads
) runs successfully:
package de.gabriel.vertretungsplan;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ActiveProfiles;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
@SpringBootTest
@ActiveProfiles("test")
class VertretungsplanApplicationTests {
@Test
void contextLoads(ApplicationContext context) {
assertThat(context).isNotNull(); // https://www.jvt.me/posts/2021/06/25/spring-context-test/
}
}
Debugging information on hibernate before the error occurs
Hibernate:
drop table if exists fach cascade
Hibernate:
drop table if exists klassen cascade
...
drop table if exists user cascade
2023-06-25T18:39:52.366+02:00 WARN 14848 --- [ main] o.h.t.s.i.ExceptionHandlerLoggedImpl : GenerationTarget encountered exception accepting command : Error executing DDL "
drop table if exists user cascade " via JDBC Statement
It seems like the error happens on dropping the "user" table? (But it doesn't seem like it is because of a reserved keyword).
As you can see I am new to unit testing and I thought it would be as simple as just annotating test methods with @Test and using the test application.properties to tell spring/junit with which db (in this case in mem h2) to use for testing, but it's just not working. Could someone please help me with what I am doing wrong?
For any one trying to help me and replicate the problem: Thank you very much, here is the whole code: https://github.com/github-gabriel/vertretungsplan-testing
-> Btw, I am only using the @ActiveProfiles and @Profile annotations because I have some beans that are meant for the main application but not for testing so I exluce them like that
答案1
得分: 1
有两个问题导致你的测试失败。第一个问题是应用程序上下文无法创建,因为Spring Boot无法检索"@EnableAutoConfiguration基础包"。它无法检索包,因为在测试配置文件处于活动状态时,你已禁用了自动配置:
@Profile("!test")
@SpringBootApplication
public class VertretungsplanApplication {
是@SpringBootApplication
启用了自动配置,但你已指示在test
配置文件处于活动状态时忽略这个类。
我假设你的意图是在运行测试时禁用CommandLineRunner
。你可以将@Profile
移到@Bean
方法:
@SpringBootApplication
public class VertretungsplanApplication {
// …
@Bean
@Profile("!test")
CommandLineRunner commandLineRunner(FachRepository fachRepository, KlasseRepository klasseRepository,
在此更改生效后,应用程序上下文将无法启动,因为Hibernate尝试创建名为user
的表,而在使用H2时,user
是保留关键字。修复此问题的一种方法是更改表的名称:
@Entity
@Table(name="usr")
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class User {
有了这两个更改,LehrerRepositoryTest
将通过。
英文:
There are two problems that are causing your tests to fail. The first problem is that the application context cannot be created due to Spring Boot being "unable to retrieve @EnableAutoConfiguration base packages". It's unable to retrieve the packages because you have disabled auto-configuration when the test profile is active:
@Profile("!test")
@SpringBootApplication
public class VertretungsplanApplication {
It's @SpringBootApplication
that enables auto-configuration, but you have indicated that this class should be ignored when the test
profile is active.
I presume that the intent was to disable the CommandLineRunner
when running tests. You can do so by moving @Profile
to the @Bean
method:
@SpringBootApplication
public class VertretungsplanApplication {
// …
@Bean
@Profile("!test")
CommandLineRunner commandLineRunner(FachRepository fachRepository, KlasseRepository klasseRepository,
With this change in place the application context will fail to start as Hibernate tries to create a table named user
and user
is a reserved keyword when using H2. One way to fix this is to change the table's name:
@Entity
@Table(name="usr")
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class User {
With these two changes in place LehrerRepositoryTest
will pass.
答案2
得分: 0
可能性1:您的测试类找不到Spring Boot主类
示例:主类的包与测试类不同
com.mainpackage.*
与 com.testpackage.*
如果是这种情况,请尝试删除
@DataJpaTest
并替换为
@SpringBootTest(classes = {com.mainpackage.YourSpringBootMainApplication.class})
可能性2:旧的Spring Boot版本2.1或更低
如果是这种情况,您需要添加以下注解
@ExtendWith
自Spring Boot 2.1以后,我们不再需要加载SpringExtension,因为它已作为元注解包含在Spring Boot测试注解中,如@DataJpaTest、@WebMvcTest和@SpringBootTest。
如果这解决了问题或有任何更改,请告诉我!
编辑:一个有效的配置结构示例:
DTO
package com.pmanaktala.scratchpadspring;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "my_dto")
public class MyDTO {
@Id
private String id;
private String name;
//getter, setter, constructors
}
Repository
package com.pmanaktala.scratchpadspring;
import org.springframework.data.jpa.repository.JpaRepository;
public interface MyDTORepository extends JpaRepository<MyDTO, String> {
}
Spring Boot Main
package com.pmanaktala.scratchpadspring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootApplication
@EnableJpaRepositories
public class ScratchPadSpringApplication {
public static void main(String[] args) {
SpringApplication.run(ScratchPadSpringApplication.class, args);
}
}
Test Class
package com.pmanaktala.scratchpadspring;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertTrue;
@DataJpaTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class LehrerRepositoryTest {
@Autowired
private MyDTORepository myDTORepository;
@BeforeAll
void init() {
myDTORepository.saveAllAndFlush(List.of(new MyDTO("123", "Test User")));
}
@AfterAll
void tearDown() {
myDTORepository.deleteAll();
}
@Test
void findById() {
Optional<MyDTO> myDTO = myDTORepository.findById("123");
assertTrue(myDTO.isPresent());
}
}
这些是您提供的内容的翻译。
英文:
<h2>Possibility 1 : Your test class cannot find spring boot main class</h2>
Example : Package for the main classes is different form the test classes\
com.mainpackage.*
vs com.testpackage.*
P
If thats the case, try removing the
@DataJpaTest
and replacing it with
@SpringBootTest(classes = {com.mainpackage.YourSpringBootMainApplication.class})
<h2>Possibility 2 : Older Spring Boot Version 2.1 or below </h2>
If thats the case, you need to add the following annotation
@ExtendWith
> As of Spring Boot 2.1, we no
> longer need to load the SpringExtension because it's included as a
> meta annotation in the Spring Boot test annotations like @DataJpaTest,
> @WebMvcTest, and @SpringBootTest.
Let me know if it fixes the issue or there is any change!
Edit: A sample configuration structure that works:
DTO
package com.pmanaktala.scratchpadspring;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "my_dto")
public class MyDTO {
@Id
private String id;
private String name;
//getter, setter, constructors
Repository
package com.pmanaktala.scratchpadspring;
import org.springframework.data.jpa.repository.JpaRepository;
public interface MyDTORepository extends JpaRepository<MyDTO, String> {
}
Spring Boot Main
package com.pmanaktala.scratchpadspring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootApplication
@EnableJpaRepositories
public class ScratchPadSpringApplication {
public static void main(String[] args) {
SpringApplication.run(ScratchPadSpringApplication.class, args);
}
}
Test Class
package com.pmanaktala.scratchpadspring;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertTrue;
@DataJpaTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class LehrerRepositoryTest {
@Autowired
private MyDTORepository myDTORepository;
@BeforeAll
void init() {
myDTORepository.saveAllAndFlush(List.of(new MyDTO("123", "Test User")));
}
@AfterAll
void tearDown() {
myDTORepository.deleteAll();
}
@Test
void findById() {
Optional<MyDTO> myDTO = myDTORepository.findById("123");
assertTrue(myDTO.isPresent());
}
}
答案3
得分: 0
我认为答案就在你的堆栈跟踪中,尽管没有实际测试它:
Caused by: java.lang.IllegalStateException: 无法检索 @EnableAutoConfiguration 基本包
at org.springframework.boot.autoconfigure.AutoConfigurationPackages.get(AutoConfigurationPackages.java:78)
这表明可能发生了 NoSuchBeanDefinitionException
,要么是在 beanFactory.getBean(BEAN, BasePackages.class)
调用中,要么是在 get()
调用中。
为了进一步调试并了解发生了什么,可以将 org.springframework.boot.autoconfigure
的日志级别提高到 DEBUG
,其次,可以尝试在 AutoConfigurationPackages.java:78
处设置断点来调试测试执行。
希望这能帮助你找到问题所在!
英文:
Without actually testing it out, I think the answer lies in your stacktrace:
Caused by: java.lang.IllegalStateException: Unable to retrieve @EnableAutoConfiguration base packages
at org.springframework.boot.autoconfigure.AutoConfigurationPackages.get(AutoConfigurationPackages.java:78)
This indicates that the a NoSuchBeanDefinitionException
occured either for the beanFactory.getBean(BEAN, BasePackages.class)
call or the get()
call.
To further debug and understand what is going on increase logging on org.springframework.boot.autoconfigure
to DEBUG
, secondly I would try to debug the test execution with a breakpoint at AutoConfigurationPackages.java:78
Hope this helps you finding the issue!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论