【问题标题】:ConstraintViolationException thrown only when trying to find in database during test仅在测试期间尝试在数据库中查找时抛出 ConstraintViolationException
【发布时间】:2021-09-17 13:35:27
【问题描述】:

我在内存数据库中使用 JPA 存储库和 H2,并且在我的应用程序中一切正常,尝试输入无效值时显示的错误如预期。然后我开始进行一些测试,但我不知道为什么在尝试执行 repository.save 时没有收到 ConstraintViolationException。 我有这门课:

public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private long id;

    @NotEmpty (message = "The user name cannot be empty")
    private String name;

    @Column(unique = true)
    @Email(message = "Please, insert a valid e-mail")
    @NotEmpty (message = "The user e-mail cannot be empty")
    private String email;

    @Column(unique = true)
    @NotEmpty(message = "The user cpf cannot be empty")
    private String cpf;

    @DateTimeFormat(pattern = "yyyy-MM-dd")
    @NotNull(message = "The user birthday cannot be empty")
    @Past
    private LocalDate birthDate;
}

这个测试通过了

@Test
    @DisplayName("Save throws ConstraintViolationException user when user is empty")
    void save_ThrowsConstraintViolationException_WhenUserIsEmpty() {
        User user = new User();
        user.setCpf("");


        Assertions.assertThatNoException()
                .isThrownBy(() -> this.userRepository.save(user));

        Assertions.assertThatExceptionOfType(ConstraintViolationException.class)
                .isThrownBy(() -> this.userRepository.findByCpf(""));

    }

有人知道发生了什么吗?

谢谢

【问题讨论】:

标签: spring-boot validation jpa h2


【解决方案1】:

在测试中我总是使用saveAndFlush(),因为save() 只调用EntityManager.persist() 并且不执行任何SQL 语句,除非你有一个带有GenerationType.IDENTITY 的ID。

所以试试这个:

Assertions.assertThatNoException()
            .isThrownBy(() -> this.userRepository.saveAndFlush(user));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-14
    • 1970-01-01
    • 1970-01-01
    • 2018-11-21
    • 1970-01-01
    • 2015-06-23
    相关资源
    最近更新 更多