简体   繁体   中英

RestController test fails with h2 database

I am trying to run a test to my RestController in my Spring boot application with h2 database. Here is some code:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
@ActiveProfiles("test")
public class E2E_EconomicOperatorAPIControllerTest {

    @Autowired
    private TestRestTemplate restTemplate;

    @Test public void test_newEconomicOperator() {
     //staff
     }
}

But when I run it, i get this error:

2018-04-03 12:16:57.084  WARN 14332 --- [       Thread-7] o.s.b.f.support.DisposableBeanAdapter    : Invocation of destroy method failed on bean with name 'inMemoryDatabaseShutdownExecutor': org.h2.jdbc.JdbcSQLException: Database is already closed (to disable automatic closing at VM shutdown, add ";DB_CLOSE_ON_EXIT=FALSE" to the db URL) [90121-196]

And here is my properties file:

spring.datasource.url=jdbc:h2:mem:testdb;MODE=Oracle;DB_CLOSE_DELAY=-1

logging.level.org.gso.admin=DEBUG
logging.level.gso.gd.client=INFO
logging.level.org.springframework.web.client=WARN
logging.level.org.springframework=WARN
logging.level.org.thymeleaf=WARN
logging.level.root=WARN

Actually, you shouldn't need to set any property for an embedded h2 database, as boot configures that for you (additionally, I think you should leave out the MODE=Oracle flag). Here's what I did: Put the following dependendy in your .pom :

<dependency>
  <groupId>com.h2database</groupId>
  <artifactId>h2</artifactId>
  <scope>test</scope>
</dependency>

Note the scope. This will load the dependency on your classpath during test (and nothing else). You should then make sure, that you have an application.properties file per environment, where you set the database wehnever you need a real one.

As an example from my app:

application-dev.properties: (note: I wanted a real db for dev, so i put in prostgres...)

spring.jpa.database=POSTGRESQL
spring.datasource.platform=postgres
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=validate
spring.database.driverClassname=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://192.168.1.100:5432/winecellar
spring.datasource.username=winecellar
spring.datasource.password=winecellar

application-test.properties:

spring.jpa.database=H2
spring.jpa.show-sql=true 
spring.jpa.hibernate.ddl-auto=none
spring.database.driverClassname=org.h2.Driver
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.datasource.username=sa
spring.datasource.password=

And I have a similar file for production settings (using postgres as well...)

Then, as long as you annotate it as you have done with @ActiveProfiles("test") , you should be fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM