1

I can't run my unit test due to an error

DataSource bean definition

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class)
public class MyBeanTest {

    @Configuration
    static class ContextConfiguration {

        @Bean
        DataSource dataSource() {
            return new EmbeddedDatabaseBuilder()
                .setType(EmbeddedDatabaseType.H2)
                .addScript("com/example/ddl.sql")
                .setSeparator(";")
                .build();
        }
    }

    // ...
}

ddl.sql content

CREATE DATABASE mydb;

Error

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in com.example.MyBeanTest$ContextConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #1 of class path resource [com/example/ddl.sql]: CREATE DATABASE mydb; nested exception is org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "CREATE DATABASE[*] MYDB "; expected "OR, FORCE, VIEW, ALIAS, SEQUENCE, USER, TRIGGER, ROLE, SCHEMA, CONSTANT, DOMAIN, TYPE, DATATYPE, AGGREGATE, LINKED, MEMORY, CACHED, LOCAL, GLOBAL, TEMP, TEMPORARY, TABLE, PRIMARY, UNIQUE, HASH, SPATIAL, INDEX"; SQL statement:

SpringBoot 1.5.3

humkins
  • 9,635
  • 11
  • 57
  • 75
  • 1
    ...and what's inside `com/example/ddl.sql`? BTW, usually that goes into `src/main/resources`. – x80486 Jun 05 '17 at 13:47
  • 5
    H2 doesn't have a `create database` statement, so that statement is a syntax error. – Mark Rotteveel Jun 05 '17 at 13:48
  • @ɐuıɥɔɐɯ I've posted its content – humkins Jun 05 '17 at 14:22
  • @Mark Rotteveel So, how to test DAOs having statements with db prefix in that case? like `select * from mydb.some_table;` – humkins Jun 05 '17 at 14:24
  • 1
    That would be [`create schema`](http://h2database.com/html/grammar.html#create_schema) instead. In the case of H2 the database is the file, and it either needs to exist, or is created when you connect to it. The schema is a subdivision inside the database. – Mark Rotteveel Jun 05 '17 at 14:46
  • Thank you, Mark! – humkins Jun 05 '17 at 18:02
  • Possible duplicate of [how to create new database in H2?](https://stackoverflow.com/questions/24372931/how-to-create-new-database-in-h2) –  Jun 23 '17 at 02:37

0 Answers0