Spring Transactional - 确保测试和产品中的可预测行为

标签 spring spring-boot kotlin spring-data-jpa junit5

我想测试我的UserService的注册方法,看起来像下面这样。

@Transactional
override fun register(userRegistration: UserRegistration): AuthDto {
    val user = userRegistration.toUserEntity()
    return try {
        val entity = userRepository.save(user)
        //entityManager.flush()
        val id = entity.getIdOrThrow().toString()
        val jwt = jwtService.createJwt(id)
        entity.toAuthDto(jwt)
    } catch (ex: PersistenceException) {
        throw UserRegistrationException(userRegistration.username, ex)
    }
}

由于 userName 上有唯一索引的User实体,我想断言在注册已经存在的用户名时会引发异常。在这种情况下,我 try catch 抛出的任何异常并重新抛出我自己的异常。

现在我的测试只需要一个现有的用户名并调用注册。

@Test fun `register twice - should throw`() {
    val existingRegistration = UserRegistration(testUserAdminName, "some", "test")

    assertThrows<UserRegistrationException> {
        userService.register(existingRegistration)
        //entityManager.flush()
    }
}

但是,除非我通过实体管理器显式刷新,否则不会引发异常。但是那我怎么能抛出我自己的异常呢?

我应该在我的 UserService 中使用 flush 吗?

最佳答案

答案来自 M. Deinum。

Flushing is done on commit and that is also where the exception is being thrown. So if you want to directly get an exception you will have to call saveAndFlush instead of save (assuming you are using the JpaRepository as a base for your own repository)



我切换到 JpaRepository我现在使用 saveAndFlush .

关于Spring Transactional - 确保测试和产品中的可预测行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61970278/

相关文章:

java - Spring 中的自定义 @ControllerAdvice 用于异常处理

spring-boot - 如何设置spring amqp发布者确认并返回?

spring - 如何在cloudbees上运行可执行jar文件(例如spring-boot)

android - 在没有 GSM 的新华为设备中禁用 Google Play 服务警告

spring - 如何配置Spring Boot和Spring Security同时支持表单登录和Google OAuth2登录

java - Geotools lib 突然从存储库中消失

android - 如何在包中将数据类作为 Parcelable 传递?

android - Jetpack-Android 仅当对象的某个属性发生变化时如何触发重组

spring - 使用 Spring 数据 JPA 获取随机记录

java - 使用 Quartz 运行 Spring Boot 应用