首页 > 解决方案 > 如何使用 JUnit 5 在 Spring Boot 中捕获 Hibernate ConstraintViolationException(或 Spring DataIntegrityViolationException?)

问题描述

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

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

细化

为了便于复制,我将我的代码缩小到只有实体和存储库,以及两个测试(一个有效,另一个是这篇文章的原因)。另外为了便于复制,我使用 H2 作为数据库。

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

我决定使用 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();
                      } );
    }
}

构建.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>

标签: javaspringspring-bootspring-data-jpajunit5

解决方案


旁注

您的项目实际上不使用 JUnit Jupiter 5.4。相反,它使用由 Spring Boot 管理的 JUnit Jupiter 5.3.2。有关解决方案,请参阅Gradle 5 JUnit BOM 和 Spring Boot 错误版本

flush()在你的@BeforeEach方法中没有必要。

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

捕获一个 ConstraintViolationException

您实际上无法捕捉到,ConstraintViolationException因为 JPA 会将其包装为 a PersistenceException,但您可以验证 aConstraintViolationException 导致PersistenceException.

为此,只需按如下方式重写您的测试。

@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);
}

捕获 DataIntegrityViolationException

如果您想从 Spring 的层次结构中捕获异常DataAccessException——例如DataIntegrityViolationException,您必须确保以EntityManager#flush()Spring 执行异常转换的方式调用该方法。

异常翻译是通过 Spring 执行的PersistenceExceptionTranslationPostProcessor,它将您的 bean 包装@Repository在代理中,以便捕获异常并翻译它们。Spring BootPersistenceExceptionTranslationPostProcessor会自动为您注册并确保您的 Spring Data JPA 存储库被正确代理。

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

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

  1. 如下重新声明您的存储库。JpaRepository使您可以直接在存储库上访问该flush()方法。

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

  2. 在您的shouldThrowExceptionOnSave()测试方法中,调用fooRepository.save(foo); fooRepository.flush();or 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);
    });
}

同样,它起作用的原因是该flush()方法现在直接在您的存储库 bean 上调用,Spring 已将其包装在一个代理中,该代理捕获 PersistenceException并将其转换DataIntegrityViolationException.


推荐阅读