I want to test the registration method of my UserService
, which looks something like the below.
@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. 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?