gpt4 book ai didi

spring - 基于 Spring Boot Hibernate JPA 的 DAO 的单元测试

转载 作者:行者123 更新时间:2023-12-04 12:53:37 25 4
gpt4 key购买 nike

我正在尝试为使用 Hibernate/JPA 实体和 DAO 的基于 Spring Boot 的应用程序编写单元测试。以下是我到目前为止所遵循的步骤:

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;

我错过了什么?

最佳答案

DilTeam,我发现你最后的评论非常重要!

Spring 不允许使用 schema.sql (无平台后缀)与 ddl-auto=create-drop 属性值。

这部分描述在这里74.3 Initialize a database using Spring JDBC :

If you want to use the schema.sql initialization in a JPA app (with Hibernate) then ddl-auto=create-drop will lead to errors if Hibernate tries to create the same tables. To avoid those errors set ddl-auto explicitly to "" (preferable) or "none". Whether or not you use ddl-auto=create-drop you can always use data.sql to initialize new data.

关于spring - 基于 Spring Boot Hibernate JPA 的 DAO 的单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29948658/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com