I decided I would like to add a h2 DB to my spring boot application for testing purposes. I added a new application-test.properties
to my folder test/resources
with all the necessary configuration. The problem is that when I run the tests, I always get the connection to the mysql database.
I can see the application-test.properties
is being used because the loggin.level
changes from DEBUG
to ERROR
in my tests.
For my MySql DB I have a file which provides the datasource
Code
application-test.properties
file
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username = sa
spring.datasource.password =
spring.datasource.driver-class-name = org.h2.Driver
spring.h2.console.enabled=false
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.format_sql=true
logging.level.org.springframework.security=ERROR
application.properties
file
mysql.database.host=localhost
mysql.database.port=3306
mysql.database.db=mydb
mysql.database.user=root
mysql.database.password=root
mysql.database.driver=mysql
logging.level.org.springframework.security=DEBUG
datasource
class
@Bean
open fun getDataSource(): DataSource? {
val dataSourceBuilder = DataSourceBuilder.create()
dataSourceBuilder.url("jdbc:$driver://$databaseHost:$databasePort/$databaseName")
dataSourceBuilder.username(databaseUser)
dataSourceBuilder.password(databasePassword)
return dataSourceBuilder.build()
}
test
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
class AdAccountControllerTest {
@Autowired
lateinit var mockMvc: MockMvc
@Test
fun `we should get unauthorized status when we dont provide credentials`() {
mockMvc.perform(get("/api/v1/ad-account"))
.andExpect(status().isOk)
.andDo(print())
}
}
question from:
https://stackoverflow.com/questions/65649125/spring-boot-application-not-using-the-db-driver-defined-in-application-test-prop 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…