如何使用JUnit 5在Spring Boot中捕获Hibernate ConstraintViolationException(或Spring DataIntegrityViolationException?)。

时间:2019-02-25 23:45:18

标签: java spring spring-boot spring-data-jpa junit5

我考虑将其命名为“ Java异常的海森堡不确定性推论”,但这是(a)太笨拙,并且(b)描述性不足。

BLUF:我试图在针对Spring Boot应用程序的JUnit 5测试中捕获一个元组被持久化到具有约束冲突的数据库表中时抛出的异常(列中标记为“唯一”的重复值)。我可以在try-catch块中捕获异常,但不能使用JUnit的“ assertThrows()”。

详细说明

为了易于复制,我将代码的范围缩小到仅实体和存储库,并且进行了两个测试(一个可行,另一个是本文的原因)。另外,为了易于复制,我将H2用作数据库。

我已经读到,存在潜在的事务范围问题,这些问题可能导致约束生成的异常不会在调用方法的范围内引发。我通过在shouldThrowExceptionOnSave()中的语句“ foos.aave(foo);”(没有“ tem.flush()”语句)周围的简单try-catch块确认了这一点。

我决定使用TestEntityManager.flush()强制事务提交/结束,并能够在try-catch块中成功捕获异常。但是,这不是预期的DataIntegrityViolationException,而是PersistenceException。

我尝试使用类似的机制(即使用TestEntityManager.flush()来在assertThrows()语句中强制执行该问题。但是,“不高兴”。

当我尝试“ assertThrows(PersistenceException.class,…”)时,该方法以DataIntegrityViolationException终止。

当我尝试“ assertThrows(DataIntegrityViolationException.class,…”)时,我实际上收到了一条JUnit错误消息,指示预期的DataIntegrityViolationException与实际的异常不匹配。这就是……javax.persistence.PersistenceException!

任何帮助/见解将不胜感激。

添加说明:shouldThrowExceptionOnSave()中的try-catch块只是为了查看捕获了什么异常。

实体类

package com.test.foo;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Foo {

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

    public Foo() {
        id   = "Default ID";
        name = "Default Name";
    }

    public Foo(String id, String name) {
        this.id   = id;
        this.name = name;
    }

    public String getId() { return id;}

    public void setName(String name) { this.name = name; }

    public String getName() { return name; }
}

存储库接口

package com.test.foo;

import org.springframework.data.repository.CrudRepository;

public interface FooRepository extends CrudRepository<Foo, String> { }

存储库测试类

package com.test.foo;

import org.hibernate.exception.ConstraintViolationException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.dao.DataIntegrityViolationException;

import javax.persistence.PersistenceException;
import java.util.Optional;

import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

@DataJpaTest
public class FooRepositoryITest {

    @Autowired
    private TestEntityManager tem;

    @Autowired
    private FooRepository foos;

    private static final int    NUM_ROWS  = 25;
    private static final String BASE_ID   = "->Test Id";
    private static final String BASE_NAME = "->Test Name";

    @BeforeEach
    public void insertFooTuples() {
        Foo foo;

        for (int i=0; i<NUM_ROWS; i++) {
            foo = new Foo(i+BASE_ID, i+BASE_NAME);
            tem.persist(foo);
        }
        tem.flush();
    }

    @AfterEach
    public void removeFooTuples() {
        foos.findAll()
                .forEach(tem::remove);
        tem.flush();
    }

    @Test
    public void shouldSaveNewTyple() {
        Optional<Foo> newFoo;
        String        newId   = "New Test Id";
        String        newName = "New Test Name";
        Foo           foo     = new Foo(newId, newName);

        foos.save(foo);
        tem.flush();

        newFoo = foos.findById(newId);
        assertTrue(newFoo.isPresent(), "Failed to add Foo tuple");
    }

    @Test
    public void shouldThrowExceptionOnSave() {
        Optional<Foo> newFoo;
        String        newId   = "New Test Id";
        String        newName = "New Test Name";
        Foo           foo     = new Foo(newId, newName);

        foo.setName(foos.findById(1+BASE_ID).get().getName());

        try {
            foos.save(foo);
            tem.flush();
        } catch(PersistenceException e) {
            System.out.println("\n\n**** IN CATCH BLOCK ****\n\n");
            System.out.println(e.toString());
        }

//        assertThrows(DataIntegrityViolationException.class,
//        assertThrows(ConstraintViolationException.class,
        assertThrows(PersistenceException.class,
                () -> { foos.save(foo);
                        tem.flush();
                      } );
    }
}

build.gradle

plugins {
    id 'org.springframework.boot' version '2.1.3.RELEASE'
    id 'java'
}

apply plugin: 'io.spring.dependency-management'

group = 'com.test'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
    mavenCentral()
}

dependencies {
    implementation('org.springframework.boot:spring-boot-starter-data-jpa')
    implementation('org.springframework.boot:spring-boot-starter-web')
    runtimeOnly('com.h2database:h2')
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'junit'
        exclude group: 'org.hamcrest'
    }
    testImplementation('org.junit.jupiter:junit-jupiter:5.4.0')
    testImplementation('com.h2database:h2')
}

test {
    useJUnitPlatform()
}

带有“ assertThrows(PersitenceException,...)”的输出

2019-02-25 14:55:12.747  WARN 15796 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 23505, SQLState: 23505
2019-02-25 14:55:12.747 ERROR 15796 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : Unique index or primary key violation: "UK_A7S9IMMDPCXHLN2D4JHLAY516_INDEX_1 ON PUBLIC.FOO(NAME) VALUES ('1->Test Name', 2)"; SQL statement:
insert into foo (name, id) values (?, ?) [23505-197]

**** IN CATCH BLOCK ****

javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
.
. (some debug output removed for brevity)
.
2019-02-25 14:55:12.869  WARN 15796 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 23505, SQLState: 23505
2019-02-25 14:55:12.869 ERROR 15796 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : Unique index or primary key violation: "UK_A7S9IMMDPCXHLN2D4JHLAY516_INDEX_1 ON PUBLIC.FOO(NAME) VALUES ('1->Test Name', 2)"; SQL statement:
insert into foo (name, id) values (?, ?) [23505-197]
2019-02-25 14:55:12.877  INFO 15796 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test: [DefaultTestContext@313ac989 testClass = FooRepositoryITest, testInstance = com.test.foo.FooRepositoryITest@71d44a3, testMethod = shouldThrowExceptionOnSave@FooRepositoryITest, testException = org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint ["UK_A7S9IMMDPCXHLN2D4JHLAY516_INDEX_1 ON PUBLIC.FOO(NAME) VALUES ('1->Test Name', 2)"; SQL statement:
insert into foo (name, id) values (?, ?) [23505-197]]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement, mergedContextConfiguration = [MergedContextConfiguration@4562e04d testClass = FooRepositoryITest, locations = '{}', classes = '{class com.test.foo.FooApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@527e5409, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@8b41920b, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@2a32de6c, [ImportsContextCustomizer@2a65fe7c key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@147ed70f, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@15b204a1, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map[[empty]]]

org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint ["UK_A7S9IMMDPCXHLN2D4JHLAY516_INDEX_1 ON PUBLIC.FOO(NAME) VALUES ('1->Test Name', 2)"; SQL statement:
insert into foo (name, id) values (?, ?) [23505-197]]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement

带有“ assertThrows(DataIntegrityViolationException,...)的输出

2019-02-25 14:52:16.880  WARN 2172 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 23505, SQLState: 23505
2019-02-25 14:52:16.880 ERROR 2172 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : Unique index or primary key violation: "UK_A7S9IMMDPCXHLN2D4JHLAY516_INDEX_1 ON PUBLIC.FOO(NAME) VALUES ('1->Test Name', 2)"; SQL statement:
insert into foo (name, id) values (?, ?) [23505-197]

**** IN CATCH BLOCK ****

javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
.
. (some debug output removed for brevity)
.
insert into foo (name, id) values (?, ?) [23505-197]
2019-02-25 14:52:16.974  INFO 2172 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test: [DefaultTestContext@313ac989 testClass = FooRepositoryITest, testInstance = com.test.foo.FooRepositoryITest@71d44a3, testMethod = shouldThrowExceptionOnSave@FooRepositoryITest, testException = org.opentest4j.AssertionFailedError: Unexpected exception type thrown ==> expected: <org.springframework.dao.DataIntegrityViolationException> but was: <javax.persistence.PersistenceException>, mergedContextConfiguration = [MergedContextConfiguration@4562e04d testClass = FooRepositoryITest, locations = '{}', classes = '{class com.test.foo.FooApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@527e5409, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@8b41920b, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@2a32de6c, [ImportsContextCustomizer@2a65fe7c key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@147ed70f, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@15b204a1, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map[[empty]]]

org.opentest4j.AssertionFailedError: Unexpected exception type thrown ==> 
Expected :<org.springframework.dao.DataIntegrityViolationException> 
Actual   :<javax.persistence.PersistenceException>
<Click to see difference>

2 个答案:

答案 0 :(得分:1)

注意事项

您的项目实际上不使用JUnit Jupiter 5.4。而是使用Spring Boot管理的JUnit Jupiter 5.3.2。有关解决方案,请参见Gradle 5 JUnit BOM and Spring Boot Incorrect Versions

您的flush()方法中无需@BeforeEach

您应删除@AfterEach方法,因为对数据库的所有更改将随测试管理的事务自动回滚。

捕获ConstraintViolationException

实际上,您无法捕获ConstraintViolationException,因为JPA会将其包装为PersistenceException,但是您可以验证{{1}引起的ConstraintViolationException }。

为此,只需按如下所示重写测试即可。

PersistenceException

正在捕获DataIntegrityViolationException

如果要从Spring的@Test public void shouldThrowExceptionOnSave() { String newId = "New Test Id"; String newName = "New Test Name"; Foo foo = new Foo(newId, newName); foo.setName(fooRepository.findById(1 + BASE_ID).get().getName()); PersistenceException exception = assertThrows(PersistenceException.class, () -> { fooRepository.save(foo); testEntityManager.flush(); }); assertTrue(exception.getCause() instanceof ConstraintViolationException); } 层次结构中捕获异常(例如DataAccessException),则必须确保以一种执行Spring异常转换的方式调用DataIntegrityViolationException方法

异常转换是通过Spring的EntityManager#flush()执行的,该转换将PersistenceExceptionTranslationPostProcessor bean封装在代理中,以捕获异常并进行转换。 Spring Boot自动为您注册@Repository,并确保正确代理了Spring Data JPA存储库。

在您的示例中,您直接在不执行异常转换的Spring Boot的PersistenceExceptionTranslationPostProcessor上调用flush()。这就是为什么您看到原始TestEntityManager而不是Spring的javax.persistence.PersistenceException的原因。

如果要断言Spring将DataIntegrityViolationException包装在PersistenceException中,则需要执行以下操作。

  1. 重新声明您的存储库,如下所示。 DataIntegrityViolationException使您可以直接在存储库中访问JpaRepository方法。

    flush()

  2. 在您的public interface FooRepository extends JpaRepository<Foo, String> {}测试方法中,调用shouldThrowExceptionOnSave()fooRepository.save(foo); fooRepository.flush();

如果您这样做,那么以下内容将通过。

fooRepository.saveAndFlush(foo);

同样,之所以可行,是因为现在@Test public void shouldThrowExceptionOnSave() { String newId = "New Test Id"; String newName = "New Test Name"; Foo foo = new Foo(newId, newName); foo.setName(fooRepository.findById(1 + BASE_ID).get().getName()); assertThrows(DataIntegrityViolationException.class, () -> { fooRepository.save(foo); fooRepository.flush(); // fooRepository.saveAndFlush(foo); }); } 方法直接在您的存储库bean上调用,Spring已将其包装在捕获flush()并进行翻译的代理中放入PersistenceException

答案 1 :(得分:0)

感谢Sam的回答。有趣的是,Sam的“哦,顺便说一句”注释之一揭示了我的代码中似乎是“真正的问题”。

下面是最终代码(几乎),几乎可以正常工作。

“几乎”,因为测试执行仍然失败,并且在尝试插入元组时违反约束似乎失败(请参见下面的控制台日志中的代码段)。

2019-02-27 09:28:50.237  INFO 4860 --- [           main] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory
Hibernate: insert into foo (name, id) values (?, ?)
2019-02-27 09:28:50.311  WARN 4860 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 23505, SQLState: 23505
2019-02-27 09:28:50.311 ERROR 4860 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : Unique index or primary key violation: "UK_A7S9IMMDPCXHLN2D4JHLAY516_INDEX_1 ON PUBLIC.FOO(NAME) VALUES ('0->Test Name', 1)"; SQL statement:
insert into foo (name, id) values (?, ?) [23505-197]
2019-02-27 09:28:50.311  INFO 4860 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test: [DefaultTestContext@1d296da testClass = FooRepositoryITest, testInstance = com.test.foo.FooRepositoryITest@6989da5e, testMethod = shouldThrowExceptionOnSave@FooRepositoryITest, testException = org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint ["UK_A7S9IMMDPCXHLN2D4JHLAY516_INDEX_1 ON PUBLIC.FOO(NAME) VALUES ('0->Test Name', 1)"; SQL statement:
insert into foo (name, id) values (?, ?) [23505-197]]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement, mergedContextConfiguration = [MergedContextConfiguration@7c7a06ec testClass = FooRepositoryITest, locations = '{}', classes = '{class com.test.foo.FooApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@45018215, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@617263ed, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@2f112965, [ImportsContextCustomizer@75d4a5c2 key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@1f3f4916, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@59d016c9, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map[[empty]]]

org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint ["UK_A7S9IMMDPCXHLN2D4JHLAY516_INDEX_1 ON PUBLIC.FOO(NAME) VALUES ('0->Test Name', 1)"; SQL statement:
insert into foo (name, id) values (?, ?) [23505-197]]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement

但是,这就是“哦,顺便说一句”注释在其中起作用的地方,它在实际测试中没有失败。它似乎在 removeFooTuples()中失败,该错误由JUnit在 shouldThrowExceptionOnSave()之后执行。但是,即使 removeFooTuples()只是尝试从表中删除任何现有的元组(并且在不预期/引发异常的测试中也成功删除了),控制台日志仍指示“插入”正在尝试。

如果注释了整个 removeFooTuples(),并且允许JUnit简单地删除表,则测试将成功执行,并以预期的结果终止。我以为 shouldThrowExceptionOnSave()中的 TestEntityManager.flush()可以避免这种情况,但是...

@DataJpaTest
public class FooRepositoryITest {

    @Autowired
    private TestEntityManager tem;

    @Autowired
    private FooRepository foos;

    private static final int    NUM_ROWS  = 1;
    private static final String BASE_ID   = "->Test Id";
    private static final String BASE_NAME = "->Test Name";

    @BeforeEach
    public void insertFooTuples() {
        Foo foo;

        for (int i = 0; i < NUM_ROWS; i++) {
            foo = new Foo(i + BASE_ID, i + BASE_NAME);
            tem.persist(foo);
        }
        tem.flush();
    }

    /* shouldThrowExceptionOnSave() executes successfully if this
     *  method is commented out
     */
    @AfterEach
    public void removeFooTuples() {
        foos.findAll()
                .forEach(tem::remove);
        tem.flush();
    }

    @Test
    public void shouldThrowExceptionOnSave() {
        String newId   = "New Test Id";
        String newName = "New Test Name";
        Foo    foo     = new Foo(newId, newName);

        foo.setName(foos.findById(0+BASE_ID).get().getName());

        assertThrows(PersistenceException.class, () -> {
                        foos.save(foo);
                        tem.flush();
                    } );
    }
}