我正在尝试为使用Hibernate / JPA实体的基于Spring Boot的应用程序编写单元测试。 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 ...',数据创建脚本。
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 :(得分:1)
DilTeam,我发现你的最后评论非常重要!
Spring不允许将 schema.sql (没有平台siffix)与 ddl-auto = create-drop 属性值一起使用。
这部分在此处描述74.3 Initialize a database using Spring JDBC:
如果要在JPA应用程序中使用schema.sql初始化(使用 Hibernate)然后ddl-auto = create-drop如果Hibernate会导致错误 尝试创建相同的表。要避免这些错误,请设置ddl-auto 明确地&#34;&#34; (优选)或&#34;无&#34;。你是否使用 ddl-auto = create-drop你总是可以使用data.sql来初始化new 数据