简体   繁体   English

Spring 事务性 - 确保测试和生产中的可预测行为

[英]Spring Transactional - Ensure predictable behavior in tests and prod

I want to test the registration method of my UserService , which looks something like the below.我想测试我的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)
    }
}

Since there is a unique index on the userName of the User entity, I would like to assert that an exception is thrown when an already existing userName is registered.由于User实体的userName上有一个唯一索引,因此我想断言当注册已经存在的 userName 时会引发异常。 In this case I try to catch whatever exception is thrown and rethrow my own.在这种情况下,我尝试捕获抛出的任何异常并重新抛出我自己的异常。

Now my test simply takes an existing userName and calls register.现在我的测试只需要一个现有的用户名并调用注册。

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

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

However, no exception is ever thrown, unless I explicitly flush via the entity manager.但是,除非我通过实体管理器显式刷新,否则不会引发异常。 But then how can I throw my own exception?但是那我怎么能抛出我自己的异常呢?

Should I use flush in my UserService?我应该在我的 UserService 中使用 flush 吗?

The answer came from M. Deinum.答案来自 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)因此,如果您想直接获取异常,则必须调用 saveAndFlush 而不是 save(假设您使用 JpaRepository 作为您自己的存储库的基础)

I switched to JpaRepository and am now using saveAndFlush .我切换到JpaRepository ,现在正在使用saveAndFlush

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM