'Spring boot tests failing - Unable to read environment variables

I am unable to build the spring boot application as spring boot tests are failing. I didn't include any tests. spring boot created a test class annotated with @SpringBootTest. It was working fine when I had db config in application.properties. I removed the hardcoded values and added it as environment variables in intelliJ and used place holders eg :

spring.datasource.url=jdbc:postgresql://${DB_HOST:dbhost}:${DB_PORT:5432}/${DB_NAME}

I tried using @PropertySource("classpath:application.properties") but that didn't work.

The application starts without any exceptions when started from IntelliJ. The issue is only when runnning mvn clean install the tests are failing.

Exception

Caused by: org.postgresql.util.PSQLException: The connection attempt failed.
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:315)
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:51)
    at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:225)
    at org.postgresql.Driver.makeConnection(Driver.java:465)
    at org.postgresql.Driver.connect(Driver.java:264)
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138)
    at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:358)
    at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206)
    at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:477)
    at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:560)
    at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115)
    at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112)
    at org.springframework.jdbc.datasource.DataSourceUtils.fetchConnection(DataSourceUtils.java:158)
    at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:116)
    at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:79)
    ... 120 common frames omitted
Caused by: java.net.UnknownHostException: dbhost


Solution 1:[1]

The issue is fixed by running a .bat file in command prompt. The file sets the env variables. When running mvn clean install in cmd tests passed.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1