I have a SpringBootTest
test that should rely on a separate class to setup an embedded Postgres and datasource.
So the Repository configuration looks like this:
package com.stream.repository.configuration
@Configuration
@ComponentScan(basePackages = arrayOf("com.stream.repository"))
@EntityScan(basePackages = arrayOf("com.stream.repository"))
@EnableJpaRepositories(basePackages = arrayOf("com.stream.repository"))
@EnableAutoConfiguration
class RepositoryConfiguration {
And the test class looks like this:
package com.stream.webapp.rest
@AutoConfigureMockMvc(addFilters = false)
@SpringBootTest(properties =
[
"spring.jpa.hibernate.ddl-auto=validate",
"spring.jpa.show-sql=true",
"spring.liquibase.enabled=true",
"spring.liquibase.change-log=classpath:db/changelog/db.changelog-master.yml",
"spring.jpa.properties.hibernate.jdbc.time_zone=UTC"
],
classes = [RepositoryConfiguration::class, AuditController::class],
webEnvironment = SpringBootTest.WebEnvironment.MOCK)
class AuditControllerTest {
And here is where it gets weird. If I run with that configuration it will complain about not finding an EntityManagerFactory
AuditService required a bean of type 'javax.persistence.EntityManagerFactory' that could not be found.
After a lot of messing around I found a solution to this problem.
If I move the RepositoryConfiguration
so that it is in the package com.stream.webapp.rest
, i.e. the same as AuditControllerTest
then it magically works.
I cannot seem to find any reason for why that is the case. So can anyone explain it and is there a way around it? because I don't want to move it. It makes a lot of sense to have it where it is.
As a side note, it is written in Kotlin, but I can't see why it would matter in this case. And this is only for testing. When running the application outside of a test scope, it works
I can also add that the AuditControllerTest
is in one module and RepositoryConfiguration
is in another. Not sure if it is relevant as it works if it is placed in the "right" package (still separate modules)
TL;DR of the question: Why does spring care that the RepositoryConfiguration
is in the same package as AuditControllerTest
?
Update: This is the current configuration: (RepositoryConfiguration
is unchanged
@AutoConfigureMockMvc(addFilters = false)
@ComponentScan("com.stream.repository")
@Configuration
@SpringBootTest(properties =
[
"spring.jpa.hibernate.ddl-auto=validate",
"spring.jpa.show-sql=true",
"spring.liquibase.enabled=true",
"spring.liquibase.change-log=classpath:db/changelog/db.changelog-master.yml",
"spring.jpa.properties.hibernate.jdbc.time_zone=UTC",
"database.dbname=stream_mapper"
],
classes = [com.stream.repository.configuration.RepositoryConfiguration::class, ExceptionMapper::class, AuditController::class],
webEnvironment = SpringBootTest.WebEnvironment.MOCK)
class AuditControllerTest {