Tuesday, December 5, 2017

Tests that use h2 in-mem db fail on Heroku

Leave a Comment

My Spring boot app has some tests that pass fine on my local, but fail on Heroku:

org.h2.jdbc.JdbcSQLException: Exception opening port "8082" (port may be in use), cause: "java.net.BindException: Address already in use (Bind failed)" [90061-196]

The data source configuration for the test profile:

@Configuration public class TestDataSourceConfiguration {     @Bean     @ConfigurationProperties(prefix = "spring.datasource")     @Profile("test")     public DataSource testDataSource() throws URISyntaxException {         return DataSourceBuilder.create().build();     } } 

application-test.properties: spring.datasource.url=jdbc:h2:mem:tesdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password=

spring.datasource.testWhileIdle = true spring.datasource.validationQuery = SELECT 1 

I know Heroku doesn't support h2, but this shouldn't be the case here as the app itself brings up the db, right?

Maybe I'm wrong, and it is not failing because of Heroku not supporting h2, but I don't have any other process listening on port 8082 (at least that I know of and being initiated from within my app)

3 Answers

Answers 1

Heroku will pass port number, you would need to use as enviroment variable with name PORT.

In order to use this variable to set your application port, you have to add line to your application-test.properties :

server.port=${PORT:8082} 

Or application-test.yml:

server:      port: ${PORT:8082} 

In case PORT is not set (like in your local environment), then default 8082 would be used.

This should cover java.net.BindException exception.

Answers 2

The db will not be auto generated unless you add this property in your properties file

spring.jpa.hibernate.ddl-auto = update 

Answers 3

This happens because of a discrepency between how tests are run on eclipse and Heroku. Eclipse runs each test separately, which means it runs each test with fresh start run of the whole application. But Heroku runs all the test classes on one machine sequentially. Therefore I have to kill the h2 server after each test class is finished running:

@AfterClass public static void tearDown() throws SQLException {     webServer.stop(); } 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment