gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 13:42:42 25 4
gpt4 key购买 nike

我想测试我的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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com