【问题标题】:Unit test for Spring boot Hibernate JPA based DAOs基于 Spring Boot Hibernate JPA 的 DAO 的单元测试
【发布时间】:2015-07-09 00:42:44
【问题描述】:

我正在尝试为使用 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 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;

我错过了什么?

【问题讨论】:

  • 发布您的组实体映射和应用程序配置的相关部分。
  • 我尝试将 import.sql 重命名为 data.sql 并创建 schema.sql 来创建组表,但仍然出现此错误。
  • 不完全确定我改变了什么,但这现在可以工作了。我唯一做的就是将所有必要的 SQL 添加到 import.sql。可能就是这个原因。
  • 你有这些字段的setter和getter吗?

标签: spring hibernate unit-testing jpa spring-boot


【解决方案1】:

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

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

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

如果您想在 JPA 应用程序中使用 schema.sql 初始化(使用 Hibernate) 那么 ddl-auto=create-drop 如果 Hibernate 会导致错误 尝试创建相同的表。为了避免这些错误设置 ddl-auto 明确地“”(首选)或“无”。无论您是否使用 ddl-auto=create-drop 你总是可以使用 data.sql 来初始化新的 数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-11
    • 2012-12-22
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    • 2020-12-11
    • 2018-07-19
    • 2016-07-23
    相关资源
    最近更新 更多