2015-04-29 67 views
7

我正在嘗試爲基於Spring Boot的應用程序使用Hibernate/JPA實體& DAO編寫單元測試。這是到目前爲止,我遵循的步驟:Spring引導的單元測試基於Hibernate JPA的DAO

1)增加以下內容的pom.xml

<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-test</artifactId> 
    <scope>test</scope> 
</dependency> 
<dependency> 
    <groupId>org.hsqldb</groupId> 
    <artifactId>hsqldb</artifactId> 
    <scope>runtime</scope> 
</dependency> 

2)在../test/resources/application.properties,我已經添加了這一點:

spring.jpa.hibernate.ddl-auto = create-drop 
spring.jpa.database = HSQL 
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.HSQLDialect 
spring.datasource.driverClassName = org.hsqldb.jdbcDriver 
spring.datasource.url: jdbc:hsqldb:mem:scratchdb 
spring.datasource.username = sa 
spring.datasource.password = 

3)在../test/resources/import.sql我已經添加了幾個 '插入...',數據創建腳本。

insert into groups(GROUP_NAME, THREAD_POOL_SIZE) values ("TEST GROUP 1", 5); 

4)單元測試看起來是這樣的:

@RunWith(SpringJUnit4ClassRunner.class) 
@SpringApplicationConfiguration(classes = Application.class) 

public class TestGroupDao { 

    @Autowired 
    GroupDao groupDao; 

    @Test 
    public void testFindByName() { 

     Group group = groupDao.findByName("TEST GROUP 1"); 
     //assertThat(group.getPoolSize(), is(equalTo(5))); 
    } 
} 

當我運行這個測試,我得到錯誤信息,如:

org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: alter table.. 
org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: user lacks privilege or object not found: PUBLIC.GROUP 

5)組實體:

@Entity 
@javax.persistence.Table(name = "groups", uniqueConstraints = { 
     @UniqueConstraint(columnNames = "GROUP_NAME"), 
}) 
public class Group { 

    // ============== 
    // PRIVATE FIELDS 
    // ============== 

    // An autogenerated id (unique for each group in the db) 
    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    @Column(name = "GROUP_ID", unique = true, nullable = false) 
    private long id; 

    @Column(name = "GROUP_NAME", unique = true, nullable = false) 
    private String name; 

我錯過了什麼?

+0

發佈您的組實體和應用程序配置的相關部分的映射。 –

+0

我嘗試將import.sql重命名爲data.sql並創建了創建組表的sql.sql,但仍然出現此錯誤。 – DilTeam

+0

不完全確定我改變了什麼,但現在正在工作。我做的唯一的事情就是將所有必需的SQL添加到import.sql中。可能是這個原因。 – DilTeam

回答

1

DilTeam,我發現你最後的評論非常重要!

春不允許使用schema.sql文件(不含平臺siffix)與DDL-AUTO =創造降 propertie值。

這部分在這裏74.3 Initialize a database using Spring JDBC描述:

如果你想使用的應用程序JPA的schema.sql文件初始化(與 休眠)然後DDL-AUTO =創造降會導致錯誤,如果休眠 嘗試創建相同的表。爲了避免這些錯誤將ddl-auto 明確設置爲「」(優選)或「無」。無論您是否使用 ddl-auto = create-drop,您始終可以使用data.sql來初始化新的 數據。